Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AnyObject is not convertible to String

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.

like image 941
user2747220 Avatar asked Jan 10 '23 14:01

user2747220


1 Answers

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) ?? ""
like image 95
vacawama Avatar answered Jan 18 '23 07:01

vacawama