Hibernia Hibernia - 1 year ago 166
iOS Question

Type 'Any' has no subscript members after updating to Swift 3

I just updated to Xcode 8 / Swift 3 and I'm getting "Type 'Any' has no subscript members" as an error to this code :

currentUserFirebaseReference.observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in
let UID = snapshot.key
let pictureURL = snapshot.value!["pictureURL"] as! String
let name = snapshot.value!["displayname"] as! String
let currentUser = Person(name: name, bio: "", UID: UID, pictureURL: pictureURL)
self.currentUserInfo = currentUser

Anywhere in my code I'm calling a snapshot.value!["something"], I'm getting this error and I can't run my code.

The only thing that has changed as far as I'm aware is the syntax of the observe, but I don't see why this isn't working now?

edit: Something like this works:

let pic = (snapshot.value as? NSDictionary)?["pictureURL"] as? String ?? ""

but I don't see what changed or what makes this necessary now vs. before.

Answer Source

In FIRDataSnapshot, value is of type id.

In Swift 3, id is imported as Any.

In the Firebase documentation, it says value can be any of NSDictionary, NSArray, NSNumber, or NSString -- clearly, subscripting doesn't make sense on all of these, especially in Swift. If you know it's an NSDictionary in your case, then you should cast it to that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download