4
votes

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.

3
There is some confusion here. If name is an NSArray, why are you treating it like a dictionary name["name"]? You index arrays with an Int and not strings. - vacawama

3 Answers

9
votes

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) ?? ""
0
votes

Try this cell.textLabel?.text = name["name"] as String

Hope it Helps!

0
votes

In Swift 3

cell.textLabel?.text = name["name"] as! String?