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 means result  will equal either the value inside  optionalInt , or 0 if  optionalInt  contains  nil .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值