Optional
nil
的類型,沒有值。聲明
@frozen enum Optional<Wrapped>
概述
每當您使用可選值時,您都會使用 Optional
類型,即使您從未鍵入單詞 Optional
也是如此。 Swift 的類型係統通常會顯示包裝類型的名稱,結尾帶有問號 (?
),而不是顯示完整的類型名稱。例如,如果變量的類型為 Int?
,那隻是 Optional<Int>
的另一種寫法。為了便於閱讀和編寫代碼,首選縮寫形式。
以下代碼示例中shortForm
和longForm
的類型相同:
let shortForm: Int? = Int("42")
let longForm: Optional<Int> = Int("42")
Optional
類型是具有兩種情況的枚舉。 Optional.none
等價於 nil
文字。 Optional.some(Wrapped)
存儲一個包裝的值。例如:
let number: Int? = Optional.some(42)
let noNumber: Int? = Optional.none
print(noNumber == nil)
// Prints "true"
您必須先解開 Optional
實例的值,然後才能在許多上下文中使用它。因為 Swift 提供了幾種安全解包可選值的方法,所以您可以選擇一種可以幫助您編寫清晰、簡潔的代碼的方法。
以下示例使用此圖像名稱和文件路徑字典:
let imagePaths = ["star": "/glyphs/star.png",
"portrait": "/images/content/portrait.jpg",
"spacer": "/images/shared/spacer.gif"]
使用鍵獲取字典的值會返回一個可選值,因此 imagePaths["star"]
具有類型 Optional<String>
或以首選方式編寫的 String?
。
可選綁定
要有條件地將 Optional
實例的包裝值綁定到新變量,請使用可選的綁定控製結構之一,包括 if let
、 guard let
和 switch
。
if let starPath = imagePaths["star"] {
print("The star image is at '\(starPath)'")
} else {
print("Couldn't find the star image")
}
// Prints "The star image is at '/glyphs/star.png'"
可選鏈
要安全地訪問包裝實例的屬性和方法,請使用後綴可選鏈接運算符(後綴 ?
)。以下示例使用可選鏈接訪問 String?
實例上的 hasSuffix(_:)
方法。
if imagePaths["star"]?.hasSuffix(".png") == true {
print("The star image is in PNG format")
}
// Prints "The star image is in PNG format"
使用 Nil-Coalescing 運算符
如果 Optional
實例是 nil
,請使用 nil-coalescing 運算符 ( ??
) 提供默認值。這裏為 imagePaths
中缺少的圖像提供了默認路徑。
let defaultImagePath = "/images/default.png"
let heartPath = imagePaths["heart"] ?? defaultImagePath
print(heartPath)
// Prints "/images/default.png"
??
運算符也適用於右側的另一個 Optional
實例。因此,您可以將多個 ??
運算符鏈接在一起。
let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath
print(shapePath)
// Prints "/images/default.png"
無條件展開
當您確定 Optional
的實例包含一個值時,您可以使用強製展開運算符(後綴 !
)無條件地展開該值。例如,失敗的Int
初始化程序的結果在下麵的示例中被無條件地解包。
let number = Int("42")!
print(number)
// Prints "42"
您還可以使用後綴 !
運算符執行無條件可選鏈接。
let isPNG = imagePaths["star"]!.hasSuffix(".png")
print(isPNG)
// Prints "true"
使用 !
無條件地展開 nil
實例會觸發運行時錯誤。
可用版本
相關用法
- Swift Optional.Publisher reduce(_:_:)用法及代碼示例
- Swift Optional.Publisher tryDrop(while:)用法及代碼示例
- Swift Optional symbolVariant(_:)用法及代碼示例
- Swift Optional popover(isPresented:attachmentAnchor:arrowEdge:content:)用法及代碼示例
- Swift Optional.Publisher debounce(for:scheduler:options:)用法及代碼示例
- Swift Optional.Publisher breakpoint(receiveSubscription:receiveOutput:receiveCompletion:)用法及代碼示例
- Swift Optional mask(alignment:_:)用法及代碼示例
- Swift Optional.Publisher mapError(_:)用法及代碼示例
- Swift Optional listSectionSeparatorTint(_:edges:)用法及代碼示例
- Swift Optional badge(_:)用法及代碼示例
- Swift Optional.Publisher catch(_:)用法及代碼示例
- Swift Optional.Publisher tryAllSatisfy(_:)用法及代碼示例
- Swift Optional.Publisher zip(_:_:_:)用法及代碼示例
- Swift Optional fullScreenCover(isPresented:onDismiss:content:)用法及代碼示例
- Swift Optional.Publisher sink(receiveValue:)用法及代碼示例
- Swift Optional keyboardType(_:)用法及代碼示例
- Swift Optional clipShape(_:style:)用法及代碼示例
- Swift Optional.Publisher scan(_:_:)用法及代碼示例
- Swift Optional.Publisher throttle(for:scheduler:latest:)用法及代碼示例
- Swift Optional preferredColorScheme(_:)用法及代碼示例
- Swift Optional.Publisher assertNoFailure(_:file:line:)用法及代碼示例
- Swift Optional background(_:ignoresSafeAreaEdges:)用法及代碼示例
- Swift Optional saturation(_:)用法及代碼示例
- Swift Optional focusSection()用法及代碼示例
- Swift Optional overlay(alignment:content:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Optional。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。