可选型

可选型Optional :是一个枚举类型,显示没有解包的值或者nil。nil值指代不能存在的值

// 枚举类型
public enum Optional<Wrapped> : ExpressibleByNilLiteral {
    case none
    case some(Wrapped)
    public init(_ some: Wrapped)
 }
// 可以用类型 + ?标识可选型,同Optional<Int>
let shortForm : Int? = Int("42")
let longForm: Optional<Int> = Int("42")
//  初始化可选型
let number: Int? = Optional.some(42)
let noNumber: Int? = Optional.none
// 强制解包
let number = Int("42")!
可选型绑定

使用”if let”,”guard let”,”switch”等将解包后的值绑定到新的变量上。

let imagePaths = ["star": "/glyphs/star.png",
                  "portrait": "/images/content/portrait.jpg",
                  "spacer": "/images/shared/spacer.gif"]
// 可选型的绑定
if let starPath = imagePaths["star"] {print(starPath)}
switch imagePaths["star"] {
case nil:  print("Couldn't find the star image")
case .some(let str):  print(str)
}
可选链

使用可选链运算符?,安全地访问包装实例的属性和方法。可选链中?地方皆可返回nil值。

// 可选链
if let isPNG = imagePaths["star"]?.hasSuffix(".png") {
    print("The star image is in PNG format")
}
nil聚合运算符

nil-coalescing operator 聚合运算符??, 在可选值是nil的时候提供一个默认值。

// nil聚合运算符
let defaultImagePath = "/images/default.png"
let heartPath = imagePaths["heart"] ?? defaultImagePath
// nil聚合运算符的链
let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath
ExpressibleByNilLiteral

可选型符合ExpressibleByNilLiteral的协议,实现init(nilLiteral: ()) ,可以直接使用nil进行初始化。

var i: Index? = nil // nil初始化
CustomReflectable

可选型符合CustomReflectable协议。

 public var customMirror: Mirror { get }
CustomDebugStringConvertible

可选型符合CustomReflectable协议。

 public var debugDescription: String { get }
操作
// 映射
 public func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> U?
 public func flatMap<U>(_ transform: (Wrapped) throws -> U?) rethrows -> U?
 // 比较
 public static func ~= (lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool
 public static func == (lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool
 public static func != (lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool
 public static func == (lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool
 public static func != (lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool
 // 默认实现的方法
 public static func != (lhs: Optional<Wrapped>, rhs: Optional<Wrapped>) -> Bool
 // Equatable协议方法
 public static func == (lhs: Wrapped?, rhs: Wrapped?) -> Bool
 public static func != (lhs: Wrapped?, rhs: Wrapped?) -> Bool

相关操作符:

// 操作符 ??
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T) rethrows -> T
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?) rethrows -> T?

可选型

猜你喜欢

转载自blog.csdn.net/m0_38055718/article/details/80507788
今日推荐