swift 學用 - 枚舉(Enum)

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)))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章