Onichan
Onichan

Reputation: 4526

Swift 1.2 [AnyObject] does not have member named 'objectForKey'

After upgrading to Swift 1.2, I got an error:

[AnyObject] does not have member named 'objectForKey'

Code:

self.photoNames = objects.map { $0.objectForKey("PhotoName") as! String }

Where objects is type [AnyObject]

Edit: (more code)

var photoNames: [String] = []
var query = PFQuery(className: "Photos")
query.findObjectsInBackgroundWithBlock ({(objects:[AnyObject]?, error: NSError?) in
    if(error == nil){
        self.photoNames = objects.map { $0.objectForKey("PhotoName") as! String }
    }
    else{
        println("Error in retrieving \(error)")
    }
        
})

Upvotes: 2

Views: 2732

Answers (2)

matt
matt

Reputation: 536026

You seem to be assuming that objects is an array of dictionaries. The thing to do is to prove it. Where you have this:

if(error == nil){
    self.photoNames = objects.map { $0.objectForKey("PhotoName") as! String }
}

Put this:

if error == nil {
    if let objects = objects as? [[NSObject:AnyObject]] {
        self.photoNames = objects.map {$0["PhotoName"] as! String}
    }
}

There is still some danger - you will crash if one of the dictionaries does not have a "PhotoName" key or if that key's value is not a string - but at least the above should compile. We can always add more safety checks later.

Upvotes: 1

Elliot Li
Elliot Li

Reputation: 452

objectForKey: is a member method of NSDictionary, not AnyObject. Here is the Reference.

If the objects is array of NSDictionary, try this:

self.photoNames = objects?.map { ($0 as? NSDictionary)?.objectForKey("PhotoName") as! String } ?? []

Upvotes: 2

Related Questions