在 Swift 中,当enum符合 时CaseIterable,“合成的 allCases 集合按声明的顺序提供案例。”
我想对CaseIterable枚举案例数组进行排序,这意味着符合Comparable. 我可以访问相同的声明顺序来确定应如何对此类对象进行排序吗?
如果没有,我的<以下实施是否合理?
enum MyEnum: CaseIterable, Comparable {
case one, two, three
}
static func < (lhs: MyEnum, rhs: MyEnum) -> Bool {
guard let lhsIndex = allCases.firstIndex(of: lhs), let rhsIndex = allCases.firstIndex(of: rhs) else {
fatalError("`MyEnum`'s implementation of `Comparable.<` found a case that isn't present in `allCases`.")
}
return lhsIndex < rhsIndex
}
Run Code Online (Sandbox Code Playgroud)
最后,有没有可能再进一步,让CaseIterable自己顺应Comparable这种方式?任何理由这将是一个坏主意?
在 Swift 5.3 及更高版本中,您可以Comparable对任何没有关联值或关联值符合Comparable.
例如:
enum Size: Comparable {
case small
case medium
case large
case extraLarge
}
let shirtSize = Size.small
let personSize = Size.large
if shirtSize < personSize {
print("That shirt is too small")
}
Run Code Online (Sandbox Code Playgroud)
我有一篇文章提供了有关此更改的信息,以及 Swift 5.3 中引入的其他功能:Swift 5.3 中有哪些新功能?
| 归档时间: |
|
| 查看次数: |
286 次 |
| 最近记录: |