可选类型(Optional)

1、可选类型本质是一个枚举,包含两个值None和Some。
String? 表示这是一个可选类型,其中一个可选值是String类型,另外一个是nil

2、常见用法及说明

1.
var str1: String? = "abc"
if str1 != nil {
//可选类型使用!解包后才能使用其中的值
//!等价于使用unsafeUnwrapped解包:let count = str1.unsafelyUnwrapped.count
   let count = str1!.count
   print(String(format: "count=%d", count))
}

2.
var _image: UIImage! 
//表示_image是一个可选值类型的变量,并且是确定有UIImage的值的,不能是nil。使用_image的时候不需要加!,直接使用即可。相当做了隐式解包,但_image本身还是可选类型

3.
var cell: CellType? = tableView.dequeueReusableCell(withIdentifier: "cellId") as? CellType
//表示cell是一个可选类型,可选的值是CellType或者nil。tableView.dequeueReusableCell(withIdentifier: "cellId")这个是对cell变量的赋初始值,由于dequeueReusableCell -> UITableViewCell, CellType是UITableViewCell的子类,为了把UITableViewCell强制转换成CellType,使用as CellType,又要保持是可选类型,加上?,所以是as?CellType

4.
let aStr: String? = "This is swift."
let bString = aStr! // 需要感叹号来取值
   
let cStr: String! = "This is Kotlin."
let dStr = cStr // 不需要感叹号来取值

你可能感兴趣的:(可选类型(Optional))