How to Use an Implicitly Unwrapped Optional in Swift

How to Use an Implicitly Unwrapped Optional in Swift


This article assumes you understand what Optionals are in Swift. If this is not the case, I recommend you read Swift Optional Explained before you continue.


In Swift, you can use an Optional where the wrapped type is expected. To do this, you simply declare the Optional type as implicitly unwrapped.



var hello: String! = "hello"

func sayHello(greeting: String) {
    print(greeting)
}

sayHello(greeting: hello) // output: hello        

This code begins by declaring an implicitly unwrapped Optional String whose value is “hello.

The type followed by an exclamation mark (!), followed by the assignment operator and followed by the value is how you declare an implicitly unwrapped Optional.


By marking the Optional as implicitly unwrapped, the compiler allows the value to be used directly where a wrapped type is expected.


The function named sayHello(_:) is declared with a parameter of type String.


At the function’s call site, the implicitly unwrapped Optional String, hello, is passed as an argument.


It’s worth noting that the variable hello is still an Optional; the operation works without errors because Swift does the unwrapping for us so that we don’t need to.


The main risk of using an implicitly unwrapped Optional is that if the value is nil and you try to access it, your app will crash. For this reason, you should limit their use to situations where you’re certain that a value will exist before it’s accessed.


要查看或添加评论,请登录