There are a few things here.
1) ? in d["title"]? misused. If you are trying to expand d["title"] , use ! but be careful because it will crash if title not a valid key in your dictionary. ( ? used for an additional chain, as if you were trying to call a method on an optional variable or to access a property. In this case, the access just did nothing if the optional ones were nil ). It doesn't seem like you're trying to expand d["title"] , so leave a value ? . Access to the dictionary always returns an optional value, because the key may not exist.
2) If you were to fix this:
let maybeTitle = d["title"] as? String
The error message changes to: Error: '(String, AnyObject)' does not convert to 'String'
The problem here is that String not an object. You need to specify NSString .
let maybeTitle = d["title"] as? NSString
Will this cause maybeTitle be an NSString? . If d["title"] does not exist or if the type is really NSNumber instead of NSString , then optional will be nil , but the application will not crash.
3) Your expression:
let title = maybeTitle as? String
does not expand the optional variable as you would like. The correct form:
if let title = maybeTitle as? String {
So, all together:
if let title = d["title"] as? NSString { // If we get here we know "title" is a valid key in the dictionary, and // we got the type right. title has now been unwrapped and is ready to use }
title will be of type NSString , which is stored in the dictionary because it contains objects. You can do everything with NSString , which you can do with String , but if you need title be String , you can do this:
if var title:String = d["title"] as? NSString { title += " by Poe" }
and if your dictionary has NSNumber :
if var age:Int = d["age"] as? NSNumber { age += 1 }