Swift 用于从所有案例中获取枚举案例索引的泛型函数
我有一个类,它的属性是枚举中的一个事例。我想编写一个泛型函数来获取枚举的Swift 用于从所有案例中获取枚举案例索引的泛型函数,swift,indexing,enums,Swift,Indexing,Enums,我有一个类,它的属性是枚举中的一个事例。我想编写一个泛型函数来获取枚举的allCases中案例的索引 我首先定义一个协议HasEnumCase,它简单地说明采用者有一个关联的caseitrable&equalable类型 protocol HasEnumCase { associatedtype TheEnum: CaseIterable & Equatable var theCase: TheEnum { get } } 这是不可编译的 func getIndexIn
allCases
中案例的索引
我首先定义一个协议HasEnumCase
,它简单地说明采用者有一个关联的caseitrable&equalable
类型
protocol HasEnumCase {
associatedtype TheEnum: CaseIterable & Equatable
var theCase: TheEnum { get }
}
这是不可编译的
func getIndexInAllCases<T: HasEnumCase>(theInstance: T) -> Int {
let allCases = T.TheEnum.allCases
let index = allCases.firstIndex(of: theInstance.theCase)
return index
}
//Cannot convert return expression of type 'T.TheEnum.AllCases.Index' to return type 'Int'
在
集合
上定义的类型索引
不必是Int
,这就是您看到错误的原因。但是,您可以使用常规约束来要求:
func getIndexInAllCases<T: HasEnumCase>(theInstance: T) -> Int where T.TheEnum.AllCases.Index == Int {
// ...
}
func getIndexInAllCases(实例:T)->Int其中T.TheEnum.AllCases.Index==Int{
// ...
}
daltonclaybrook的推理和回答是正确的:问题在于索引的类型
我发现我还可以根据allCases
的结果创建一个数组,编译器将完成其余的工作
func getIndexInAllCases<T: HasEnumCase>(theInstance: T) -> Int {
let allCases = Array(type(of: theInstance).TheEnum.allCases)
let index = allCases.firstIndex(of: theInstance.theCase)!
return index
}
func getindexin所有情况(实例:T)->Int{
让allCases=Array(类型:instance.thenum.allCases)
设index=allCases.firstIndex(of:instance.theCase)!
回报指数
}
func getIndexInAllCases(instance:T)->T.thenum.AllCases.Index{返回T.thenum.AllCases.firstIndex(of:theInstance.theCase)!}
func getIndexInAllCases<T: HasEnumCase>(theInstance: T) -> Int {
let allCases = Array(type(of: theInstance).TheEnum.allCases)
let index = allCases.firstIndex(of: theInstance.theCase)!
return index
}