首先让我们定义Optional
Optional值是某种类型(Int
,String
,UIColor
等)的容器,它可以包含值(1
,"Hello world"
,.greenColor()
等),也可以是 nil
。
let anOptionalInt: Int? = 1
let anotherOptionalInt: Int? = nil
![图片描述](https://istack.dev59.com/tNmSW.webp)
在Swift中,当我们看到一个Optional值时,我们会想:
好的,这个值可能包含实际值或者nil
强制解包
这是一种提取Optional内包含值的操作。
这个操作很危险,因为你在告诉编译器:我确定这个Optional值包含一个真实的值,请将其提取出来!
let anOptionalInt: Int? = 1
let anInt: Int = anOptionalInt!
现在,anInt
包含值 1。
![输入图像描述](https://istack.dev59.com/253ui.webp)
如果我们对包含nil
的可选值进行强制解包,会导致fatalError
,应用程序会崩溃并且无法恢复。
let anotherOptionalInt: Int? = nil
let anotherInt = anotherOptionalInt!
fatal error: unexpectedly found nil while unwrapping an Optional value
隐式解包可选项
当我们定义一个隐式解包可选项时,我们定义了一个容器,每次读取它时将自动进行强制解包。
![输入图像描述](https://istack.dev59.com/BWIeE.webp)
var text: String! = "Hello"
如果现在我们阅读 text
let name = text
我们得到的不是Optional String
,而是普通的String
,因为text
自动解包了它的内容。
但是text
仍然是一个可选值,所以我们可以在其中放置nil
值。
text = nil
但是一旦我们读到它(它包含nil
),我们就会遇到致命错误,因为我们正在展开一个包含nil
的可选项。
let anotherName = text
fatal error: unexpectedly found nil while unwrapping an Optional value