問題

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

例如,我如何做類似的事情:

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

結果示例:

 ♠
♥
♦
♣
 

  最佳答案

Swift 4.2+

Swift 4.2 (使用Xcode 10)開始,只需將協議一致性新增到CaseIterable以從allCases獲益:

 extension Suit: CaseIterable {}
 

然後這將列印所有可能的值:

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

與早期Swift版本的相容性(3.x和4.x)

只是模仿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
 

  相同標籤的其他問題

swiftstringenumsenumerate