我最近将我的应用程序从Swift 2.3升级到Swift 3.0,当我这样做时,我收到以下错误:
Type 'Dictionary<NSObject, AnyObject>?' has no subscript members
出现的功能如下:
class func getSSIDConnectionName() -> String? {
var currentSSID: String?
let interfaces = CNCopySupportedInterfaces()
if interfaces == nil {
print("Got nil up here")
return nil
}
let interfaces2:CFArray! = interfaces
for i in 0..<CFArrayGetCount(interfaces2) {
let interfaceName: UnsafeRawPointer = CFArrayGetValueAtIndex(interfaces2, i)
let rec = unsafeBitCast(interfaceName, to: AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)" as CFString)
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData["SSID"] as? String
} else {
print("Got nil down here")
return nil
}
}
return currentSSID
}
我收到“当前SSID =”行的错误。这段代码在Swift 2.3中工作得很好,不幸的是,我对标记为“不安全”的东西并不强烈,所以如果答案深入研究这些区域,那么如果你能尽可能简单地解释它,那将是最有帮助的。
感谢阅读!
答案 0 :(得分:7)
更改
let interfaceData = unsafeInterfaceData! as Dictionary!
到
let interfaceData = unsafeInterfaceData! as NSDictionary
原因:unsafeInterfaceData
是CFDictionary。 CFDictionary可以直接转换为NSDictionary,因为它们是免费桥接的。这足以让我们订阅,所以我们可以使用像interfaceData["SSID"]
这样的表达式。
答案 1 :(得分:4)
除了@matt所说的,你的代码可以大大简化,
特别是通过将返回值从CNCopySupportedInterfaces()
转换为Swift [String]
数组,
和可选的绑定if let
而不是针对nil
进行测试
并强行打开:
func getSSIDConnectionName() -> String? {
guard let interfaces = CNCopySupportedInterfaces() as? [String] else {
return nil
}
for ifname in interfaces {
if let interfaceData = CNCopyCurrentNetworkInfo(ifname as CFString) as? [String: Any],
let currentSSID = interfaceData["SSID"] as? String {
return currentSSID
}
}
return nil
}
答案 2 :(得分:1)
键或下标的数据类型需要“NSObject”。 SWIFT 3似乎强迫您将其转换为正确的数据类型。如果你有
currentSSID = interfaceData?[String("SSID") as NSObject] as? String
或
currentSSID = interfaceData?["SSID" as NSObject] as? String
汇编将消失。只是要注意其他人的答案也可以。