将 Swift 1 语法重写为 Swift 3 - "Type Any has no subscript value"

Rewriting Swift 1 syntax to Swift 3 - "Type Any has no subscript value"

var peerIds = [String]()
var peersInfos: NSMutableDictionary!

self.peersInfos.addEntries(from: [peerId: ["videoView": NSNull(), "videoSize": NSNull(), "isAudioMuted": NSNull(), "isVideoMuted": NSNull()]])

let videoView = (self.peersInfos[peerId]?["videoView"])!
let videoSize = (self.peersInfos[peerId]?["videoSize"])!
let isAudioMuted = (self.peersInfos[peerId]?["isAudioMuted"])!

这是在 Swift 1 中编写的应用程序的语法,Xcode 8 已将其转换为 Swift 3。它抛出一个错误 "type Any has no subscript value"。我不知道如何解决这个问题,请帮助我!!!

由于在这种情况下您可能想使用常用的 Swift 词典,因此您应该更改

var peersInfos: NSMutableDictionary!

var peersInfos: [String: Any]!

首先,即使您的问题已经解决,您也会遇到著名的 Unexpectedly found nil while unwrapping an Optional value 错误,因为可变字典已声明但未初始化。

出现错误type Any has no subscript value是因为字典的值默认为Any,编译器需要知道所有下标的静态类型对象。

字典 peersInfos 包含嵌套字典,因此将其声明为本机 Swift 类型

var peerIds = [String]()
var peersInfos = [String:[String:Any]]()

那你可以写

self.peersInfos[peerId] = ["videoView": NSNull(), "videoSize": NSNull(), "isAudioMuted": NSNull(), "isVideoMuted": NSNull()]

if let info = self.peersInfos[peerId] {
    let videoView = info["videoView"]!
    let videoSize = info["videoSize"]!
    let isAudioMuted = info["isAudioMuted"]!
}