enum 的 allValues

Posted by Genie on June 20, 2020

enum 在 java 或其他的语言中都有allValues,swift 中无,我们如何来实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
enum Suit: String, EnumType {
    case A
    case B
    case C
    case D

    static var allValues: [Suit] {
        return [.A, .B, .C, .D]
    }
}

enum Rank: Int, EnumType {
    typealias RawValue = Int

    case Ace = 1
    case Two, Three
    case Jack

    var description: String {
        switch self {
        case .Ace:
            return "A"
        case .Jack:
            return "J"
        default:
            return String(self.rawValue)
        }
    }

    static var allValues: [Rank] {
        return [.Ace, .Two, .Three, Jack]
    }
}

protocol EnumType {
    static var allValues: [Self] { get }
}

for suit in Suit.allValues {
    for rank in Rank.allValues {
        print("\(suit.rawValue)\(rank.rawValue)")
    }
}