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)))