我想实现一个泛型结构来处理许多属性。这些属性中的每一个(质量、缺陷...)是枚举数组,两者都符合Options协议。当我声明OptionType符合Options协议,并因此声明为RawRepresentable时,我很难理解这个错误,更广泛地说,我很难理解如何管理泛型枚举类型。欢迎任何指导!
非常感谢,乔
struct Property {
var options: [OptionType]
var label: String {
"\(OptionType.Type.self)"
}
var allSortedOptions: [OptionType] {
let allOptions = OptionType.allCases as! [OptionType]
return allOptions.sorted(by: {$0.rawValue < $1.rawValue})
//Won't compile: Binary operator '<' cannot be applied to two 'OptionType.RawValue' operands
}
}
protocol Options: CaseIterable, RawRepresentable {}
extension Options {}
enum OptionQualities: String, Options {
case polite, handsome, smart, funny, enjoyable, articulated
}
enum OptionFlaws: String, Options {
case lazy, chatty, oftenLate, dirty, agressive, complaining
}发布于 2021-02-25 14:03:31
你只需要添加一个约束到你的协议选项RawRepresentable RawValue to String:
protocol Options: CaseIterable, RawRepresentable where RawValue == String { }或者,如果您可能有其他枚举类型,则可以简单地将RawValue限制为Martin R建议的类似协议
protocol Options: CaseIterable, RawRepresentable where RawValue: Comparable { }请注意,不需要强制转换allCasesas! [OptionType]
var allSortedOptions: [OptionType] {
OptionType.allCases.sorted(by: { $0.rawValue < $1.rawValue })
}https://stackoverflow.com/questions/66363042
复制相似问题