Search code examples
swiftdictionarypfuser

Swift: '(String) -> AnyObject?' does not have a member named 'subscript'


I am trying to convert a PFUser (from Parse.com) to a dictionary of [String : AnyObject] type, but I got the following error that seems very confusing to me. I did google search and found the following two SO questions, which, however, still not helpful in solving my problem:

Error:

'(String) -> AnyObject?' does not have a member named 'subscript'

Found these two posts: relevant SO post 1, relevant SO post 2

My PFUser has the keys: fullName, email, latitude, longitude, and linkedInUrl.

Since the types of the values for the above keys are a mix of String and Double. so I am trying to create the following Dictionary:

var userData : [String: AnyObject] = [
            "fullName" : pfUser.valueForKey("fullName") as? String,
            "latitude" : pfUser.valueForKey("latitude") as? Double,
            "longitude" : pfUser.valueForKey("longitude") as? Double,
            "email" : pfUser.valueForKey("email") as? String,
            "linkedInUrl" : pfUser.valueForKey["linkedInUrl"] as? String
        ]

The version of my XCode is 6.4. I appreciate your help.


Solution

  • You are declaring wrong type of userData. It must be [String: AnyObject?] because your values are optionals.

    And don't forget to change this line "linkedInUrl" : pfUser.valueForKey["linkedInUrl"] as? String with this line "linkedInUrl" : pfUser.valueForKey("linkedInUrl") as? String.

    And your code will be:

    var userData : [String: AnyObject?] = [
            "fullName" : pfUser.valueForKey("fullName") as? String,
            "latitude" : pfUser.valueForKey("latitude") as? Double,
            "longitude" : pfUser.valueForKey("longitude") as? Double,
            "email" : pfUser.valueForKey("email") as? String,
            "linkedInUrl" : pfUser.valueForKey("linkedInUrl") as? String
        ]