Swift Optional Explained

Swift Optional Explained


Maybe it contains a value, maybe it doesn’t!


In Swift, an Optional is a type of enumeration that represents a wrapped value or the absence of a value.

You can declare an Optional using the Optional initializer.


var sayHello = Optional("Hello")
print(sayHello) // Output: Optional("Hello")        

In this code, sayHello is a variable holding a reference to an Optional String. Printing the variable produces the output Optional(“Hello”).



var sayHello: String? = "Hello"
print(sayHello) // Output: Optional("Hello")        

You can also express an optional with syntactic sugar. To do this, use the name of the wrapped type followed by a question mark. This code produces the same result as the one above.

It’s worth noting that an Optional String is not the same as a String.



func optionalHello(greeting: String?) {
    
    print(greeting)
}

var myGreeting = optionalHello(greeting: sayHello)
myGreeting // output: Optional("Hello")        

Here, optionalHello(_:) is a function that expects an Optional String as a parameter. At the function’s call site, the variable sayHello can be used as a parameter value because it holds an Optional String.



var greetUser = "Good Morning"

func optionalHello(greeting: String?) {
    
    print(greeting)
}

var myGreeting = optionalHello(greeting: greetUser)
myGreeting // output: Optional("Good Morning")        

If a function expects an Optional String as a parameter, you can also pass it a String and it will implicitly wrap it — meaning that it will convert the String into an Optional String. This is because parameter passing behaves like an assignment, therefore it wraps the value.



var sayHello = Optional("Hello")

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

var myGreeting = optionalHello(greeting: sayHello) // Error: Value of optional type 'String?' must be unwrapped to a value of type 'String'        

Attempting to pass an Optional String to a function that expects a String does not convert the String into an Optional String; instead, we get the following error.

Value of optional type ‘String?’ must be unwrapped to a value of type ‘String’

If you want to use an Optional where the type of value it wraps is expected, then you must first unwrap the Optional.


Unwrapping an Optional


var sayHello = Optional("Hello")

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

var myGreeting = optionalHello(greeting: sayHello!)
myGreeting // output: Hello        

This is the same code as before, however, take note of the exclamation mark (!) that follows the variable sayHello. This is how to unwrap an Optional.

Now that the Optional String has been unwrapped, the value that’s printed is the StringHello,” rather than the Optional(“Hello”).


As you can see, Optionals are a great way of handling variables or constants which may or may not contain values.

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