Search code examples
dictionaryswiftdowncast

down casting an element of a dictionary


When I try to downcast an element of a dictionary, I get a syntax error:

let adDict:Dictionary<String, AnyObject> = DidonWebServices.sharedInstance.adAtIndex (indexPath.row)


let titleString = adDict["description"] as? String      // error: 'String' is not a subtype of '(String, AnyObject)'

If I replace the previous line by:

let title:AnyObject? = adDict["description"]
let titleString = title as? String

the compiler is happy and the code is working.

I don't understand the compiler error. Any idea ?


Solution

  • It's because the subscript in Dictionary returns an optional:

    subscript (key: KeyType) -> ValueType?
    

    Meaning you have to unwrap the optional before you can downcast:

    let titleString = adDict["description"]! as? String
    

    As of Beta 3 you can access the value directly without downcasting, like this:

    let titleString = adDict["description"]