rmp rmp - 3 months ago 21
Swift Question

Optional Chaining in one step?

Why does this work (Example 1):

if let numString:String = Model.selectedLocation?.zip{
let callString:String = String(format:"tel:%@",numString)
//more code here
}


But not this (Example 2):

if let numString:String = String(format:"tel:%@",Model.selectedLocation?.zip){
//more code here
}


In the second example, Xcode throws an error and wants
zip
to be unwrapped like:
String(format:"tel:%@",(Model.selectedLocation?.zip)!)


but if I do that the app will crash when
zip
is nil.

QUESTION:
Is there a way to make the second example above work or is it not possible/correct?

Answer

Strictly spoken Example 2 is neither optional binding nor optional chaining because String(format...) returns an non-optional String and the format parameter must be non-optional, too.

Example 1 is the correct and recommended syntax to handle the optionals.