1

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.

Community
  • 1
  • 1
TonyW
  • 18,375
  • 42
  • 110
  • 183

2 Answers2

2

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
    ]
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
1

There are two mistakes in your current code

First one is, use ( ) instead of using [ ] to get the value using the key in the following line.

"linkedInUrl" : pfUser.valueForKey["linkedInUrl"] as? String

Second one is, use an exclamation point instead to unwrap the optional.

Your code should look like what's shown below.

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 other solution is, making the dictionary declaration as [String: AnyObject?] to hold the optional values.

Shamsudheen TK
  • 30,739
  • 9
  • 69
  • 102