How is optional binding used in swift?

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

    From the Apple Doc

    Optional Binding

    To conditionally bind the wrapped value of an Optional instance to a new variable, use one of the optional binding control structures, including if let, guard let, and switch.

    if let starPath = imagePaths["star"] {
        print("The star image is at '\(starPath)'")
    } else {
        print("Couldn't find the star image")
    }
    

    Optional Chaining

    To safely access the properties and methods of a wrapped instance, use the postfix optional chaining operator (postfix ?). The following example uses optional chaining to access the hasSuffix(_:) method on a String? instance.

            if let isPNG =imagePaths["star"]?.hasSuffix(".png") {
                print("The star image is in PNG format")
            }
            // Prints "The star image is in PNG format"
    

提交回复
热议问题