Swift开发系列之 - 可选类型Optional

132 阅读1分钟

什么是可选类型

swift编译器要求开发者明确变量/属性的状态,即确定是否不为nil。如果不确定,则使用变量/属性时需要针对两种场景进行处理。

表示变量/属性有两种状态:1是nil,2.是个确定值。可选类型的定义如下(实际上是枚举类型):

public enum Optional<Wrapped> : ExpressibleByNilLiteral {
 
    /// The absence of a value.
    ///
    /// In code, the absence of a value is typically written using the `nil`
    /// literal rather than the explicit `.none` enumeration case.
    case none
 
    /// The presence of a value, stored as `Wrapped`.
    case some(Wrapped)
 
    /// Creates an instance that stores the given value.
    public init(_ some: Wrapped)
}

语法规则,下面两种写法等价

let shortForm: Int? = Int("42")
let longForm: Optional<Int> = Int("42")

什么是解包解包

Optional类型通常不能直接使用,需要解包后获取nil或者确定的值,才能为程序所用?

如何解包解包

1.gurad let

let name: String? = "Antoine van der Lee"
guard let unwrappedName = name else {
    return
}
print(unwrappedName.count)

2.if let

2.if let

let name: String? = "Antoine van der Lee"
if let unwrappedName = name {
    print(unwrappedName.count)
}

3.使用“??” 运算符

let name: String? = "Antoine van der Lee"
print(name?.count ?? 0)

  1. 使用"!"运算符强制解包,如果值为nil则抛出fatalError异常,除非能确保有值,通常不推荐使用
var name: String? = "Antoine van der Lee"
print(name!.count)

  1. 链式解包
struct BlogPost {
    let title: String?
}
 
let post: BlogPost? = BlogPost(title: "Learning everything about optionals")
print(post?.title?.count ?? 0)

Demo

截屏2022-05-15 13.43.24.png

参考文档

www.avanderlee.com/swift/optio…

developer.apple.com/documentati…