Swift optional type implementation

Swift optional type是用enum去實作,以下為Optional type的部分source code:

public enum Optional<Wrapped>: ExpressibleByNilLiteral {
case none
case some(Wrapped)
public init(_ some: Wrapped) { self = .some(some) }
public init(nilLiteral: ()) {
self = .none
}
@inlinable
public static func ==(lhs: Wrapped?, rhs: Wrapped?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l == r
case (nil, nil):
return true
default:
return false
}
}
…..
}
view raw gistfile1.txt hosted with ❤ by GitHub

由上面我們可以知道:

  1. 一個非nil的值會被指定到case some(Wrapped),而一個nil的值會被指定到case none
  2. 比較兩個值是否相等時,只要有一個變數是optional,在進行比較前,兩個變數都會被轉換成Optional type,再進行比較
    Note: 詳細原文說明在[ref 1]的第386行

ref 1: https://github.com/apple/swift/blob/main/stdlib/public/core/Optional.swift

%d 位部落客按了讚: