协议
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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。