我正在尝试向next枚举添加一个var。我能够为特定的枚举执行此操作,但希望对其进行一般性扩展,以便我可以通过使用协议指定枚举来从枚举值中获取“下一个”枚举案例,例如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
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将CaseIterable约束扩展Self到Equatable. 然后,你只需要找到后,该指数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]
}
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是限制AllCases为BidirectionalCollection. 这将允许您获取枚举的最后一个元素,检查它是否等于 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)!)]
}
}
Run Code Online (Sandbox Code Playgroud)
扩展 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) }
}
Run Code Online (Sandbox Code Playgroud)
extension CaseIterable where AllCases: BidirectionalCollection {
var last: Self { allCases.last! }
private static func index(before i: Index) -> Index { allCases.index(before: i) }
}
Run Code Online (Sandbox Code Playgroud)
extension CaseIterable where Self: Equatable {
var index: Index { Self.firstIndex(of: self) }
private static func firstIndex(of element: Self) -> Index { allCases.firstIndex(of: element)! }
}
Run Code Online (Sandbox Code Playgroud)
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)] }
}
Run Code Online (Sandbox Code Playgroud)
游乐场测试;
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
325 次 |
| 最近记录: |