Swift optional type是用enum去實作,以下為Optional type的部分source code:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| } | |
| ….. | |
| } |
由上面我們可以知道:
- 一個非nil的值會被指定到case some(Wrapped),而一個nil的值會被指定到case none
- 比較兩個值是否相等時,只要有一個變數是optional,在進行比較前,兩個變數都會被轉換成Optional type,再進行比較
Note: 詳細原文說明在[ref 1]的第386行
ref 1: https://github.com/apple/swift/blob/main/stdlib/public/core/Optional.swift