【问题标题】:Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String' Swift Error无法下标“[NSObject : AnyObject]?”类型的值带有“字符串”类型的索引的 Swift 错误
【发布时间】:2018-03-19 14:02:15
【问题描述】:

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

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
            }
        }

【问题讨论】:

  • 究竟是哪一行?

标签: ios swift xcode


【解决方案1】:

唯一使用下标的行是:

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

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

尝试将此行更改为:

let interfaceData = unsafeInterfaceData! as [String: AnyObject]

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

【讨论】:

    【解决方案2】:

    你可以试试

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      相关资源
      最近更新 更多