对于Swift的Enum,文档上没有说的
今天无意发现一个东西, 但是在文档上看了很多遍都没找到, 但是亲测是可行的, 那到底是什么呢?
以前我们定义枚举 会这样:
enum Hello { case Item( String, Int) case Healthy( Float, Float) }
文档上也是这么写的,但是在开发中,例如:
enum FeastTransform { //(let cityID: Int?, let catoryID: Int?, let typeID: Int? , let sort: String?, let number: String?, let time: String, let cdbID: Int, let placeTypeID: Int, let banner: Int, let nextCursor: String, count:Int) case ThemesOfPublicT(Int, Int, Int, String, String, String, Int, Int, Int, String, Int) case ThemesOfPublic(String, Int?, ID , Count, List?) case Theme(ID) case ThemesOfMaster(ID, ID) case ThemesOfParticipator(ID, ID) case ThemesOfMyself(String?, ID, Count) case ThemesOfMasterBookable(ID) case ThemesUpdate(ID, String, String, String, String, String, DictArray, DictArray) }
为了可读性,我们顶多做到就是用
typealias ID = String typealias Name = String typealias URL = String typealias Count = Int typealias Price = String typealias KeyWorkds = String typealias List = Array<String>
但是上面的可读性还是 so ugly!
但是今天无意发现这么个东西,😄。真的不要谢我,真心是无意的。原来枚举可以这么玩:
enum Hello { case Item(name: String, age: Int) case Healthy(height: Float, weight: Float) }
给他的参数命名, 玩过Haskell的伙伴应该说句 nice!这个真心nice,可读性立马 提升到一个水平, 都不用这个 `typealias KeyWorkds = String`。
extension Hello { func para() -> Dictionary<String, Any> { switch self { case .Item(let name , let age): return ["name": name, "age": age] case .Healthy(let height, let weight): return ["height": height, "weight":weight] } } } let a = Hello.Healthy(height: 12, weight: 13) a.para()
有兴趣的伙伴们也可以试试哇.
使用Where语句:
extension Media { var publishedAfter1930: Bool { switch self { case let .Book(_, _, year) where year > 1930: return true case let .Movie(_, _, year) where year > 1930: return true case .WebSite: return true // same as "case .WebSite(_)" but we ignore the associated tuple value default: return false } } }