In Swift, how can I iteratively fetch all cases of enum? The answer is CaseIterable. By following the CaseIterable protocol, a collection of allCases can be retrieved through the allCases attribute.

Get all cases

enum Direction: CaseIterable {case East case West case North case South} let count = direction.allcases. count // AllCases {print(direction)} east West north SouthCopy the code

All operations of collections are supported

For this set, we can not only traverse it, but also perform filter, map higher-order operations on it.

enum Direction: Int, CaseIterable {case case west case north case south east = 0} / / let the filter operation result = Direction. AllCases. Filter { $0. RawValue > 1} for direction in result {print(direction)} // Let caseList = direction. allCases .map({ "\($0)" }) .joined(separator: ", ") // caseList == "north, south, east, west" print(caseList)Copy the code

How to use CaseIterable when enum has union values

When enum complies with the protocol, the compiler automatically provides the function implementation required by CaseIterable, such as the code above. But an enum does not automatically provide a function implementation when it has a combined value. It’s up to us to implement what the CaseIterable protocol requires.

enum Barcode: CaseIterable {
    case upc(Int, Int, Int)
    case qrCode(String)
}
Copy the code

The preceding code cannot be compiled and an error message is displayed indicating that Type ‘Barcode’ does not conform to protocol ‘CaseIterable’.

Change to the following code will do:

enum Barcode: CaseIterable {
    typealias AllCases = [Barcode]
    static var allCases: [Barcode] = [.upc(0, 0, 0), .qrCode("")]

    case upc(Int, Int, Int)
    case qrCode(String)
}

let count = Barcode.allCases.count
Copy the code

Now that we’ve implemented AllCases and AllCases we can use it just as before.