協議
Case
CaseIterable
一種提供其所有值的集合的類型。
聲明
protocol CaseIterable
概述
符合CaseIterable
協議的類型通常是沒有關聯值的枚舉。使用 CaseIterable
類型時,您可以使用類型的 allCases
屬性訪問所有類型案例的集合。
例如,此示例中聲明的 CompassDirection
枚舉符合 CaseIterable
。您可以通過 CompassDirection.allCases
訪問案例數量和案例本身。
enum CompassDirection: CaseIterable {
case north, south, east, west
}
print("There are \(CompassDirection.allCases.count) directions.")
// Prints "There are 4 directions."
let caseList = CompassDirection.allCases
.map({ "\($0)" })
.joined(separator: ", ")
// caseList == "north, south, east, west"
符合CaseIterable 協議
編譯器可以自動為任何枚舉提供 CaseIterable
要求的實現,而在其案例中沒有關聯值或 @available
屬性。綜合 allCases
集合按聲明順序提供案例。
通過在枚舉的原始聲明中聲明與CaseIterable
的一致性,您可以在定義自己的自定義枚舉時利用此編譯器支持。上麵的CompassDirection
示例演示了這種自動實現。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift CollectionDifference firstIndex(of:)用法及代碼示例
- Swift Collection prefix(upTo:)用法及代碼示例
- Swift ContiguousArray forEach(_:)用法及代碼示例
- Swift CollectionOfOne contains(_:)用法及代碼示例
- Swift ClosedRange.Index ..<(_:)用法及代碼示例
- Swift Collection first用法及代碼示例
- Swift Character lowercased()用法及代碼示例
- Swift ContiguousArray insert(contentsOf:at:)用法及代碼示例
- Swift ClosedRange index(_:offsetBy:)用法及代碼示例
- Swift CollectionOfOne compactMap(_:)用法及代碼示例
- Swift CollectionDifference contains(where:)用法及代碼示例
- Swift CollectionOfOne last(where:)用法及代碼示例
- Swift Collection dropLast(_:)用法及代碼示例
- Swift ContiguousArray reserveCapacity(_:)用法及代碼示例
- Swift Comparable ...(_:)用法及代碼示例
- Swift ClosedRange.Index ..<(_:_:)用法及代碼示例
- Swift ContiguousArray lexicographicallyPrecedes(_:)用法及代碼示例
- Swift ContiguousArray elementsEqual(_:)用法及代碼示例
- Swift ContiguousArray isEmpty用法及代碼示例
- Swift ContiguousArray suffix(from:)用法及代碼示例
- Swift CollectionDifference forEach(_:)用法及代碼示例
- Swift CollectionDifference firstIndex(where:)用法及代碼示例
- Swift CollectionDifference prefix(_:)用法及代碼示例
- Swift CollectionOfOne firstIndex(of:)用法及代碼示例
- Swift CollectionDifference randomElement()用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 CaseIterable。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。