可选项的本质是enum
类型
public enum Optional<Wrapped>: ExpressibleByNilLiteral {
case none
case some(Wrapped) //关联值
public init(_ some: Wrapped)
}
平时写的可选项可以等价其他写法:
var age: Int? = 10
age = 20
age = nil
//等价下面两种
var age1: Optional<Int> = Optional<Int>.some(10)
var age2: Optional<Int> = Optional.some(10)
var age3: Optional<Int> = .some(10)
var age4: Optional<Int> = 10
var age5 = Optional(10)
age1 = .some(20)
age1 = .none
var age: Int? = nil
var age1 = Optional<Int>.none
var age2: Optional<Int> = .none
网友评论