讓 enum 型別遵從 protocol Identifiable
Published in
Jun 4, 2021
開發 SwiftUI App 時,我們時常會讓資料型別遵從 protocol Identifiable,讓資料可以識別區分,方便搭配 ForEach 或 List。
不過如果資料的型別是 enum,可以讓它遵從 protocol Identifiable 嗎 ? 它要如何定義 id 呢 ? 有以下幾種方法。
方法 1: 利用 enum 本身當 id
enum 預設遵從 protocol Hashable,所以它的每個 case 本來就可以區分,可以當成 id。
enum Animal: Identifiable {
case cat
case dog
case rabbit
var id: Self {
self
}
}
方法 2: 利用 hashValue 當 id
enum 預設遵從 protocol Hashable,每個 case 將擁有一個可以區分彼此的數字,儲存在 hashValue,所以我們可以將 hashValue 當成 id。
enum Animal: Identifiable {
case cat
case dog
case rabbit
var id: Int {
hashValue
}
}
方法 3: 利用 rawValue 當 id
當 enum 有 rawValue 時,我們可以將 rawValue 當成 id。
enum Animal: String, Identifiable {
case cat
case dog
case rabbit
var id: String {
rawValue
}
}