【问题标题】:Swift 3 upgrade: Type 'Dictionary<NSObject, AnyObject>?' has no subscript membersSwift 3 升级:键入'Dictionary<NSObject, AnyObject>?'没有下标成员
【发布时间】:2016-10-15 04:23:37
【问题描述】:

我最近将我的应用程序从 Swift 2.3 升级到了 Swift 3.0,当我升级时,我收到了以下错误:

Type 'Dictionary&lt;NSObject, AnyObject&gt;?' 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 中运行良好,不幸的是,我不擅长标记为“不安全”的东西,所以如果答案深入到这些区域,如果你能尽可能简单地解释它,那将是最有帮助的。

感谢阅读!

【问题讨论】:

    标签: swift swift3


    【解决方案1】:

    改变

    let interfaceData = unsafeInterfaceData! as Dictionary!
    

    let interfaceData = unsafeInterfaceData! as NSDictionary
    

    原因:unsafeInterfaceData 是一个 CFDictionary。 CFDictionary 可以直接转换为 NSDictionary,因为它们是免费桥接的。这足以让我们下标,所以我们可以使用像interfaceData["SSID"] 这样的表达式。

    【讨论】:

      【解决方案2】:

      除了@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
      }
      

      【讨论】:

        【解决方案3】:

        键或下标的数据类型需要“NSObject”。 SWIFT 3 似乎迫使您将其转换为正确的数据类型。如果你有

        currentSSID = interfaceData?[String("SSID") as NSObject] as? String
        

        currentSSID = interfaceData?["SSID" as NSObject] as? String
        

        编译将消失。请注意,其他答案也可以。

        【讨论】:

          猜你喜欢
          • 2014-12-17
          • 2015-01-09
          • 1970-01-01
          • 2017-06-20
          • 1970-01-01
          • 1970-01-01
          • 2017-01-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多