对于Swift的Enum,文档上没有说的

今天无意发现一个东西, 但是在文档上看了很多遍都没找到, 但是亲测是可行的, 那到底是什么呢?

以前我们定义枚举 会这样: 

 

1
2
3
4
enum Hello {
    case Item( String,  Int)
    case Healthy( Float,  Float)
}

 文档上也是这么写的,但是在开发中,例如: 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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)
  
    }

 为了可读性,我们顶多做到就是用

1
2
3
4
5
6
7
typealias ID = String
 typealias Name = String
 typealias URL = String
 typealias Count = Int
 typealias Price = String
 typealias KeyWorkds = String
 typealias List = Array<String>

 但是上面的可读性还是 so ugly!

但是今天无意发现这么个东西,😄。真的不要谢我,真心是无意的。原来枚举可以这么玩: 

1
2
3
4
5
6
7
enum Hello {
 
    case Item(name: String, age: Int)
 
    case Healthy(height: Float, weight: Float)
 
}

 给他的参数命名, 玩过Haskell的伙伴应该说句  nice!这个真心nice,可读性立马 提升到一个水平, 都不用这个 `typealias KeyWorkds = String`。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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语句: 

1
2
3
4
5
6
7
8
9
10
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
    }
  }
}

 

posted @   OHeroJ  阅读(550)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示