如何将值与CaseIterable枚举关联



我想使用与以下大小写可迭代枚举相关的值。但当我使用关联值时,它会给出一个错误Type 'DetailRow' does not conform to protocol 'CaseIterable'。有什么办法做到这一点吗?

enum DetailRow: CaseIterable {
case history
case statements
case visibility(Bool)
case whatIsIn
case faqs
case terms
}

当您有关联的值时,您需要自己实现它:

enum DetailRow: CaseIterable {
case history
case statements
case visibility(Bool)
case whatIsIn
case faqs
case terms
static let allCases: [DetailRow] = [
.history, .statements, .visibility(true), .visibility(false), .whatIsIn, 
.faqs, .terms
]
}

Bool不是CaseIterable,嵌套事例可迭代性的自动合成尚未实现。你需要自己做。

extension Bool: CaseIterable {
public static var allCases: [Self] { [false, true] }
}
extension DetailRow: CaseIterable {
static var allCases: [Self] {
[.history, .statements]
+ Bool.allCases.map(visibility)
+ [.whatIsIn, .faqs, .terms]
}
}

最新更新