Take a look at the Optional conversations section in documents. In the example you are quoting, there is not much difference. But in other cases, the if-let construct allows you to get the expanded value obtained from a series of additional references and method calls, without using implicit unpacking, which can lead to your application crash if you did not take into account all possible bindings for the value in the chain.
This is also useful if you want to avoid recalculating the value. You can use it in much the same way as you use the assignment in the (Obj) C conditional expression (remember if (self = [super init]) ).
For example, if the optional test result comes from a computed property:
var optionalName: String? { get { if checkTouchID() { return "John Appleseed" } else { return nil } } } var greeting = "Hello!" if optionalName != nil { greeting = "Hello, \(optionalName)" }
Paste this onto the playing field along with the implementation of checkTouchID() , which returns checkTouchID() , and you will immediately see in the results checkTouchID() that the optionalName getter performs twice. (This would be a problem in a more realistic scenario, because you probably don't want code like this to implicitly checkTouchID() or downloadFromServer() or billApplePay() twice.) If you use the if-let construct instead, ll will execute only once.
In a series of chain options (for example, if let johnsStreet = john.residence?.address?.street in the documents linked above), you do not want to rewrite the whole chain in the body of the if , and even more so, reprogram it.
rickster
source share