How is optional binding used in swift?

前端 未结 9 2726
太阳男子
太阳男子 2020-12-10 13:07

In swift the following syntax is allowed for flow control

if let constantName = someOptional {
    statements
}

In this context wh

9条回答
  •  无人及你
    2020-12-10 13:22

    if let constantName = someOptional {
        statements
    }
    

    Basically what is happening here is that if someOptional has a non-nil value, constantName is assigned someOptional value for the scope of this if-statement.

    In terms of semantics, the order of how things happen is A) someOptional is checked for nil, B) and then it is assigned to constantName, and then finally, C) statements in the if-block are executed.

    Usually, the value of doing something like this is that it prevents the app from crashing if you otherwise have a nil-value. It is worth noting that the nil in Swift if different from Objective-C because it is more powerful than simply a pointer.

    Also, if someOptional is a Bool that is False, do note that it will still execute that if-block because it is not checking for true/false but rather the presence/absence of value. The presence of False renders the if-block true.

提交回复
热议问题