小编典典

如何枚举字符串类型的枚举?

all

enum Suit: String {
    case spades = "♠"
    case hearts = "♥"
    case diamonds = "♦"
    case clubs = "♣"
}

例如,我该怎么做:

for suit in Suit {
    // do something with suit
    print(suit.rawValue)
}

结果示例:

♠
♥
♦
♣

阅读 91

收藏
2022-03-07

共1个答案

小编典典

斯威夫特 4.2+

Swift 4.2(使用
Xcode
10)开始,只需添加协议一致性即可CaseIterableallCases.
要添加此协议一致性,您只需在某处编写:

extension Suit: CaseIterable {}

如果枚举是您自己的,您可以直接在声明中指定一致性:

enum Suit: String, CaseIterable { case spades = "鈾�"; case hearts = "鈾�"; case diamonds = "鈾�"; case clubs = "鈾�" }

然后下面的代码将打印所有可能的值:

Suit.allCases.forEach {
    print($0.rawValue)
}

与早期 Swift 版本(3.x 和 4.x)的兼容性

如果您需要支持 Swift 3.x 或 4.0,您可以通过添加以下代码来模仿 Swift 4.2 的实现:

#if !swift(>=4.2)
public protocol CaseIterable {
    associatedtype AllCases: Collection where AllCases.Element == Self
    static var allCases: AllCases { get }
}
extension CaseIterable where Self: Hashable {
    static var allCases: [Self] {
        return [Self](AnySequence { () -> AnyIterator<Self> in
            var raw = 0
            var first: Self?
            return AnyIterator {
                let current = withUnsafeBytes(of: &raw) { $0.load(as: Self.self) }
                if raw == 0 {
                    first = current
                } else if current == first {
                    return nil
                }
                raw += 1
                return current
            }
        })
    }
}
#endif
2022-03-07