不能下标'[NSObject:AnyObject]类型的值吗?索引类型为'String'Swift Error

时间:2018-03-19 14:02:15

标签: ios swift xcode

我的鳕鱼是那个,这个错误出现在课程的最后一行,我该怎么做才能解决它?

public class SSID {
            class func fetchSSIDInfo() -> String {
                var currentSSID = ""
                if let interfaces = CNCopySupportedInterfaces() {
                    for i in 0..<CFArrayGetCount(interfaces) {
                        let interfaceName: UnsafeRawPointer = CFArrayGetValueAtIndex(interfaces, 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
                        }
                    }
                }
                return currentSSID
            }
        }

2 个答案:

答案 0 :(得分:1)

使用下标的唯一行是:

let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData?["SSID"] as String

使用如下字符串访问:interfaceData?["SSID"]要求您以不同方式定义字典,当前字典声明为[NSObject: AnyObject]但要使用字符串下标,则需要[String: AnyObject]

尝试将此行更改为:

let interfaceData = unsafeInterfaceData! as [String: AnyObject]

注意:最好使用if而不是强制使用!

进行展开

答案 1 :(得分:0)

你可以尝试

if  let interfaceData = unsafeInterfaceData! as? [String:Any]
{
    currentSSID = interfaceData["SSID"] as? String
}