rmp rmp - 6 months ago 58
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
to be unwrapped like:

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

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


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.