user3903998
user3903998

Reputation: 3

Parse/Swift - "AnyObject is not convertible to String

I'm trying to populate a table view with items from an array of PFObjects:

var obj: PFObject = self.usersArray[indexPath.row] 
cell.textLabel?.text = obj.objectForKey("username") 

But if I do it that way I get the compiler error: "AnyObject is not convertible to String"
That's the way I always did it with Objective-C, how do I sort this out?

Upvotes: 0

Views: 2326

Answers (2)

Mihai Fratu
Mihai Fratu

Reputation: 7663

Why not write your code in a simpler way and stop using objectForKey. In the latest Parse library the PFObject supports direct access to a custom object's properties by using the [] notation (documentation).

Also why is textLabel an optional? You should unwrap that before using it. So replace ? with ! or remove it completely if textLabel is not declared as an optional.

Basically your code could look like this:

var obj: PFObject = self.usersArray[indexPath.row] 
cell.textLabel!.text = obj["username"] as NSString // Remove ! if textLabel is not an optional

Let me know if this works for you.

Upvotes: 0

Greg
Greg

Reputation: 9168

You need to cast explicitly to avoid this error:

cell.textLabel?.text = obj.objectForKey("username") as String

This is because obj.objectForKey(...) returns an object of type AnyObject, and Swift does not permit implicitly casting this to another type, while Objective-C does (imagine it being compulsory to write (NSString *)obj.objectForKey(...) in Objective-C).

Upvotes: 3

Related Questions