Search code examples
swift3syntaxskylink

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"])!

This is the syntax from an app that was written in Swift 1 and Xcode 8 has converted it into Swift 3 to this. It is throwing an error saying "type Any has no subscript value". I have no clue how to fix this, please help me!!!


Solution

  • First of all even if your issue has been solved you will get the famous Unexpectedly found nil while unwrapping an Optional value error because the mutable dictionary is declared but not initialized.

    The error type Any has no subscript value occurs because the value of a dictionary is Any by default and the compiler needs to know the static type of all subscripted objects.

    The dictionary peersInfos contains a nested dictionary so declare it as native Swift type

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

    then you can write

    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"]!
    }