1. 枚舉作爲字典的key, 需要繼承協議 Hashable
至於協議的方法,可以自己重新實現,也可以不用再實現
2. 在switch、guard之外提取關聯值
根據反射機制提取關聯值
protocol Associated {
}
extension Associated {
var associated: (label:String, value: Any?) {
get {
let mirror = Mirror(reflecting: self)
if let associated = mirror.children.first {
return (associated.label!, associated.value)
}
print("WARNING: Enum option of \(self) does not have an associated value")
return ("\(self)", nil)
}
}
}
enum HashTestEnum: Hashable, Associated {
case hashNorth(Int, String, Float)
case hashSouth(Int)
var name: String {
return "test name"
}
}
let v = HashTestEnum.hashNorth(120,"string 12", 0.33)
let ass = v.associated
print(ass) //(label: "hashNorth", value: Optional((120, "string 12", 0.33)))