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)))
发布了34 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ZhangWangYang/article/details/104516909