你也喜歡數 enum 嗎兄弟

array.count 可以, string.count 行, enum.count 卻無法,沒道理對吧?

在此提供幾招填補 enum 不可 count 的遺憾:

 

用迴圈來數


enum SectionType: Int {
case header = 0
case list
static let count: Int = {
var max: Int = 0
while let _ = SectionType(rawValue: max) { max += 1 }
return max
}()
}
print(SectionType.count) // 2

乍看之下還不錯吧,不過這個方法有幾個小缺陷

  • enum 必須宣告 raw value 為 Int 型別,並且 raw value 需要是照順序排序的,若是亂數的 raw value 則不適用
  • 每次宣告 enum 都要寫這一遍

有沒有更簡單的方式呢?有!

 

手動宣告


enum SectionType: Int {
case header = 0
case list
static let count = 2
}
print(SectionType.count) // 2

這個方法暴力有效,直接使用工人智慧賦予 enum 一個 count 變數

但是這個方法又會有以下問題:

  • 有可能 enum case 增減之後沒有更新 count 的值而造成錯誤
  • 看起來頗遜

有沒有簡單優雅又不失風範的方法?有!

 

Enum 佐 CaseIterable feat. allCases.count


enum SectionTypes: CaseIterable {
case header
case list
}
print(SectionTypes.allCases.count) // 2

讓 enum conform CaseIterable 這個 protocol 之後,就可以使用 enum.allCases 取得包含所有 case 的 array,

就很容易拿到 enum cases 的總數啦~