A type that provides a collection of all of its values.
SDK
- Xcode 10.0+
Framework
- Swift Standard Library
Declaration
protocol CaseIterable
Overview
Types that conform to the Case protocol are typically enumerations without associated values. When using a Case type, you can access a collection of all of the type’s cases by using the type’s all property.
For example, the Compass enumeration declared in this example conforms to Case. You access the number of cases and the cases themselves through Compass.
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"
Conforming to the CaseIterable Protocol
The compiler can automatically provide an implementation of the Case requirements for any enumeration without associated values or @available attributes on its cases. The synthesized all collection provides the cases in order of their declaration.
You can take advantage of this compiler support when defining your own custom enumeration by declaring conformance to Case in the enumeration’s original declaration. The Compass example above demonstrates this automatic implementation.