mavericklab
mavericklab

Reputation: 23

swift 3 Type 'Any' error

So I had a perfectly working project using swift 2. Then I updated xcode and it converted the code to Swift 3. Now im getting this error every time I call snapshot. I'm using Firebase as my backend. This is my code.

import Foundation
import Firebase
import FirebaseDatabase
import FirebaseAuth


struct User {

var username: String!
var email: String!
var photoUrl: String!
var country: String!
var ref: FIRDatabaseReference?
var key: String!


init(snapshot: FIRDataSnapshot){

    key = snapshot.key
    username = snapshot.value!["username"] as! String
    email = snapshot.value!["email"] as! String
    photoUrl = snapshot.value!["photoUrl"] as! String
    country = snapshot.value!["country"] as! String
    ref = snapshot.ref

}




}

I'm getting the error that reads: Type 'Any' has no subscript members. This error is on the lines that have snapshot.value in them. Does anyone have any idea on how to fix this?

Upvotes: 1

Views: 1160

Answers (3)

Chad Pavliska
Chad Pavliska

Reputation: 1273

The snapshot.value can be a Dictionary, Array, String, etc. Also, in Swift 3 there was a change to how to represent a Dictionary. It went from [String:AnyObject] to [String:Any].

The right way to do this is to make sure to safely unwrap all values like this:

// swift 3    
if let userDict = snapshot.value as? [String:Any] {
    username = userDict["username"] as? String
}

Upvotes: 0

Dmytro Rostopira
Dmytro Rostopira

Reputation: 11165

before Xcode 8 beta 6 snapshot.values was of type [String:AnyObject]. Just cast it

guard snapshot.exists() else { return }
let value = snapshot.value as! [String:AnyObject]
username = value["username"] as! String

Upvotes: 1

Jans
Jans

Reputation: 11250

What about something like:

let values = snapshot.value as! Dictionary<String,String>
username = values["username"]
...

Upvotes: 4

Related Questions