加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 笔记(七)

发布时间:2020-12-14 07:14:38 所属栏目:百科 来源:网络整理
导读:我的主力博客:半亩方塘 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

我的主力博客:半亩方塘


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


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 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:

authorName = 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 .
Author is Matt Gallowayfatal error: unexpectedly found nil while unwrapping an Optional valueififunwrappedAuthorNameelseifunwrappedAuthorNameif letifnilnilresultoptionalIntoptionalIntnil

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读