Swift 筆記(七)

我的主力博客:半畝方塘


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 or nil.
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 contain nilThe 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


2、Consider the following declaration:

var authorName: String? = "Matt Galloway"  

There are two different methods you can use to unwrap this optional. The first is known as force 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:

Author is Matt Galloway  

You should use force unwrapping sparingly. To see why, consider what happens when the optional doesn't contain a value:

authorName = nil
var unwrappedAuthorName = authorName!
print("Author is \(unwrappedAuthorName)")

The code produces the following runtime error:

fatal error: unexpectedly found nil while unwrapping an Optional value

The error happens because the variable contains no value when you try to unwrap it.

Fortunately, Swift includes a feature known as if 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 theif side of the if statement, within which you automatically unwrap the unwrappedAuthorName variable because you know it's safe to do so. If the optional doesn't contain a value, then the code executes theelse side of the if statement. In that case, the unwrappedAuthorName variable doesn't even exist.

You can see how if let binding is much safer than force unwrapping, and you 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 the if part 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 nil, you'll use a default value. This is called nil coalescing. Here is how it works:

var optionalInt: Int? = 10
var result: Int = optionalInt ?? 0  

The nil coalescing happens on the second line, with the double question mark (??). This line meansresult will equal either the value inside optionalInt, or 0 if optionalInt contains nil.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章