我想实现一个通用结构来处理许多属性。这些属性(品质、缺陷……)都是enum数组,它们都符合Options协议。由于我声明OptionType符合Options协议,因此也符合RawRepresentable,因此我很难理解错误,更一般地说,很难理解如何管理泛型枚举类型。欢迎大家多多指教!
很多谢谢,乔
struct Property<OptionType: Options> {
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
}
你只需要添加一个约束到你的协议选项rawrepresable RawValue到String:
protocol Options: CaseIterable, RawRepresentable where RawValue == String { }
或者如果你可能有其他枚举类型,你可以像Martin R
建议的那样,简单地将RawValue约束为Comparable协议protocol Options: CaseIterable, RawRepresentable where RawValue: Comparable { }
注意不需要转换allCasesas! [OptionType]
var allSortedOptions: [OptionType] {
OptionType.allCases.sorted(by: { $0.rawValue < $1.rawValue })
}