具有关联类型的泛型结构实现协议

generics struct implementing protocol with associated type

我在尝试为我的 ui 元素定义容器时遇到了困难。

因为我想要封装一个非唯一标签的东西,一个可以是任何可比较对象的值以及一个成为首选选项的概念,我想出了以下协议:

protocol OptionProtocol:Comparable {
    associatedtype Key:Comparable
    associatedtype Value:Comparable

    var key:Key { get set }
    var value:Value { get set }
    var main:Bool { get set }

    static func <(lhs: Self, rhs: Self) -> Bool

    static func ==(lhs: Self, rhs: Self) -> Bool

}

extension OptionProtocol {
    static func <(lhs: Self, rhs: Self) -> Bool {
        let equalKeys = lhs.key == rhs.key
        return  equalKeys ? lhs.value < rhs.value : lhs.key < rhs.key
    }

    static func ==(lhs: Self, rhs: Self) -> Bool{
        return  (lhs.value == rhs.value) && (lhs.key == rhs.key)
    }
}

现在我想在通用结构中实现协议,但我不知道如何实现。我想做的是

struct Option<Key, Value>: OptionProtocol  {
    var key:Key
    var value:Value
    var main:Bool
}

但是编译器抱怨 Type 'Option<Key, Value>' does not conform to protocol 'OptionProtocol'

任何指针都会有帮助

答案很简单。我需要在结构中约束 Key 和 Value。 以下结构按预期编译

struct Option<Key, Value>:OptionProtocol where Key:Comparable, Value:Comparable {
    var key:Key
    var value:Value
    var main:Bool
}