Optionals
1、Optionals are Swift's solution to the problem of representing both a value and the absence of a value. An optional type is allowed to reference either a value ornil
.
Think of an optional as a Box: it either contains a value,or it doesn't. When it doesn't contain a value,it's said to containnil
.The Box itself always exists; it's always there for you to open and look inside.
Non-optional types are guaranteed to have an actual value.
You declare an optional type by using the following Syntax:
var errorCode: Int?
Setting the value is simple. You can either set it to an
Int
,like so:
errorCode = 100
var authorName: String? = "Matt Galloway"
There are two different methods you can use to unwrap this optional. The first is known asforce unwrapping,and you perform it like so:
var unwrappedAuthorName = authorName! print("Author is \(unwrappedAuthorName)")The exclamation mark after the variable name tells the compiler that you want to look inside the Box and take out the value. Here's the result:
You should use force unwrapping sparingly. To see why,consider what happens when the optional doesn't contain a value:
Author is Matt Gallowayfatal error: unexpectedly found nil while unwrapping an Optional valueififunwrappedAuthorNameelseifunwrappedAuthorNameif letifnilnilresultoptionalIntoptionalIntnilauthorName = nil var unwrappedAuthorName = authorName! print("Author is \(unwrappedAuthorName)")
The code produces the following runtime error:
The error happens because the variable contains no value when you try to unwrap it.
Fortunately,Swift includes a feature known asif let binding,which lets you safely access the value inside an optional. You use it like so:
if let unwrappedAuthorName: String = authorName { print("Author is \(unwrappedAuthorName)") } else { print("No author.") }
This special Syntax rids the type of the optional. If the optional contains a value,then the code executes theside of thestatement,within which you automatically unwrap thevariable because you know it's safe to do so. If the optional doesn't contain a value,then the code executes theside of thestatement. In that case,thevariable doesn't even exist.
You can see howbinding is much safer than force unwrapping,andyou should opt for it whenever possible.
You can even unwrap multiple values at the same time,like so:
let authorName: String? = "Matt Galloway" let authorAge: Int? = 30 if let name: String = authorName,age: Int = authorAge { print("The author is \(name) who is \(age) years old.") } else { print("No author or no age.") }
This code unwraps two values. It will only execute thepart of the statement when both optionals contain a value.
There's one final and rather handy way to unwrap an optional. You use it when you want to get a value out of the optional no matter what-and in the case of,you'll use a default value. This is callednil coalescing. Here is how it works:
var optionalInt: Int? = 10 var result: Int = optionalInt ?? 0
The coalescing happens on the second line,with the double question mark (??). This line means will equal either the value inside contains .