以下代码(编译时没有错误)检索特定 CaseIterable 枚举类型中元素的索引
public enum MyEnum : CaseIterable {
case ONE, TWO, THREE
public func ordinal() -> Int? {
return MyEnum.allCases.firstIndex(of: self)
}
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个通用函数来处理所有 CaseIterable 枚举。
如果我尝试:
public extension CaseIterable {
public func ordinal() -> Int? {
return CaseIterable.allCases.firstIndex(of: self)
}
}
Run Code Online (Sandbox Code Playgroud)
我收到一个编译器错误“ Member 'allCases' cannot be used on value of protocol type 'CaseIterable'; use a generic constraint instead”,这是非常合乎逻辑的,因为实际的枚举类型未知”。
当我尝试时CaseIterable<T>,我收到另一个错误,因为 CaseIterable 未声明为泛型类型。
有办法吗?
我喜欢Swift允许使用枚举方法.我正在尝试使用方法,但我正在寻找一种更可扩展的方法:
enum CopyState{
case binary, hex, both
init(){
self = .both
}
mutating func next() {
if self == .binary{
self = .hex
} else if self == .hex {
self = .both
} else if self == .both{
self = .binary
}
}
}
var state = CopyState()
state.next()
Run Code Online (Sandbox Code Playgroud)
我想基本上将枚举转换为整数,并以总模数选项的模数递增
添加或删除枚举选项很麻烦(我使用的是last()和next()方法).
我正在尝试向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)