gpt4 book ai didi

swift - 如何在 Swift 中为 CaseIterable 枚举实现 'next' 属性

转载 作者:行者123 更新时间:2023-12-03 19:42:31 25 4
gpt4 key购买 nike

我正在尝试添加 next var 到一个枚举。我可以为特定枚举执行此操作,但希望对其进行一般扩展,以便我可以通过使用协议(protocol)指定枚举来从枚举值中获取“下一个”枚举案例,例如 CaseNextIterable

enum MyEnum: CaseIterable { // 'next' here is possible thanks to 'CaseIterable' protocol
case a, b, c
// returns the next case, or first if at end of sequence
// ie. a.next == b, c.next == a
var next: Self {
var r: Self!
for c in Self.allCases + Self.allCases { // not efficient
if r != nil {
r = c
break
}
if c == self {
r = self
}
}
return r
}
}

最佳答案

您可以扩展CaseIterable约束 SelfEquatable .那么你只需要找到firstIndex之后的索引即可您的CaseItareble枚举并返回该位置的元素。如果索引等于 endIndex在所有情况下只返回第一个元素。

extension CaseIterable where Self: Equatable {
private var allCases: AllCases { Self.allCases }
var next: Self {
let index = allCases.index(after: allCases.firstIndex(of: self)!)
guard index != allCases.endIndex else { return allCases.first! }
return allCases[index]
}
}

另一种选择是约束 AllCasesBidirectionalCollection .这将允许您获取枚举的最后一个元素,检查它是否等于 self 并返回第一个元素,而无需迭代整个集合:
extension CaseIterable where Self: Equatable, AllCases: BidirectionalCollection {
var allCases: AllCases { Self.allCases }
var next: Self {
guard allCases.last != self else { return allCases.first! }
return allCases[allCases.index(after: allCases.firstIndex(of: self)!)]
}
}

扩展 CaseIterable 下一个和上一个属性:
extension CaseIterable {
typealias Index = AllCases.Index
var first: Self { allCases.first! }
private var allCases: AllCases { Self.allCases }
private static func index(after i: Index) -> Index { allCases.index(after: i) }
}
extension CaseIterable where AllCases: BidirectionalCollection {
var last: Self { allCases.last! }
private static func index(before i: Index) -> Index { allCases.index(before: i) }
}
extension CaseIterable where Self: Equatable {
var index: Index { Self.firstIndex(of: self) }
private static func firstIndex(of element: Self) -> Index { allCases.firstIndex(of: element)! }
}
extension CaseIterable where Self: Equatable, AllCases: BidirectionalCollection {
var previous: Self { first == self ? last : allCases[Self.index(before: index)] }
var next: Self { last == self ? first : allCases[Self.index(after: index)] }
}

游乐场测试;
enum Enum: CaseIterable {
case a,b,c
}

let value: Enum = .c

let next = value.next // a
let next2 = next.next // b
let next3 = next2.next // c

let previous = value.previous // b
let previous2 = previous.previous // a
let previous3 = previous2.previous // c

关于swift - 如何在 Swift 中为 CaseIterable 枚举实现 'next' 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61250833/

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