gpt4 book ai didi

swift - 我可以按声明顺序对枚举的案例进行排序吗?

转载 作者:行者123 更新时间:2023-12-03 09:28:50 25 4
gpt4 key购买 nike

在 Swift 中,当 enum符合 CaseIterable , "The synthesized allCases collection provides the cases in order of their declaration."

我想对 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
}

最后,有没有可能更进一步,使 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")
}

我有一篇文章提供了有关此更改的信息以及 Swift 5.3 中引入的其他功能: What’s new in Swift 5.3?

关于swift - 我可以按声明顺序对枚举的案例进行排序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61781053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com