The code below returns the error "AnyObject is not convertible to String" :
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Podcast")
var query = PFQuery(className: "Podcast")
query.selectKeys(["name", "artist" ])
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
let name: NSArray = objects as NSArray
println("objects \(name)")
cell.textLabel?.text = name["name"]
}
}
if I add "as NSString" next to "name["name"]". then I get the error "type Int does not confirm to StringLiteralConvertible"
Any ideas please? I am pulling data from Parse.
name["name"]
will return a value of type AnyObject?
. It is optional because dictionary
look ups always return optionals since the key might be invalid. You should conditionally
cast it to type NSString
which is an object type and then use optional binding (if let
)
to bind that to a variable in the case where the loop up does not return nil
:
if let myname = name["name"] as? NSString {
cell.textLabel?.text = myname
}
or if you want to use an empty string if "name" is not a valid key, the nil coalescing operator ??
comes in handy:
cell.textLabel?.text = (name["name"] as? NSString) ?? ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With