user2747220 user2747220 - 11 months ago 61
Swift Question

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.

Answer Source

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) ?? ""
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download