有没有办法将枚举的所有值复制到字典中,而不在任何FOR循环中轮询它们?
例如,在此枚举中:
enum FruitPriority: String {
case PEARS
case ORANGES
case APPLES
}
要从枚举中调用某个函数,请执行以下操作:
var fruitPriorityArray: [String : Int] = FruitPriority.someFunction()
并获取此结果(根据哈希值排序):
["PEARS": 0, "ORANGES": 1, "APPLES": 2]
首选项是只对枚举进行一次调用。
谢谢您。
最佳答案
enum FruitPriority: String, CaseIterable {
case PEARS
case ORANGES
case APPLES
}
let result = FruitPriority.allCases.enumerated().reduce([String: Int]()) { dict, fruit in
var dict = dict
dict[fruit.element.rawValue] = fruit.offset
return dict
}
print(result)
结果是:
[“梨”:0,“橘子”:1,“苹果”:2]
对于Swift 4.1及更早版本,实现
CaseIterable
:#if swift(>=4.2)
#else
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
return AnyIterator {
let current = withUnsafeBytes(of: &raw) { $0.load(as: Self.self) }
guard current.hashValue == raw else {
return nil
}
raw += 1
return current
}
})
}
}
#endif
原post的
CaseIterable
实现。