如何枚举String类型的枚举?enum Suit: String {
case spades = "♠"
case hearts = "♥"
case diamonds = "♦"
case clubs = "♣"}例如,我该怎么做:for suit in Suit {
// do something with suit print(suit.rawValue)}结果示例:♠
♥
♦
♣
3 回答
慕的地6264312
TA贡献1817条经验 获得超6个赞
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- 3 回答
- 0 关注
- 2171 浏览
添加回答
举报
0/150
提交
取消
