How is optional binding used in swift?

前端 未结 9 2741
太阳男子
太阳男子 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:30

    Think of it like this: An optional is just an Enum with an associated value.

    enum OptionalValue {
        case None
        case Some(T)
    }
    

    When you assign to an optional, under the hood the .Some enum value is used, with an associated value that you gave. If you assign it to nil, it's given the value None, with no associated value.

    if let constantName = someOptional {}
    

    Does the if on the enum. If it's .Some, then the constant is assigned the associated value, and the block is executed. Otherwise nothing happens.

提交回复
热议问题