简体   繁体   English

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

[英]generics struct implementing protocol with associated type

I am a bit stuck trying to define a container for my ui elements. 尝试为ui元素定义容器时,我有些困惑。

As I wanted something that encapsulates a non unique label, a value that can be any comparable object and a concept of being the preferred option I came up with the following protocol: 当我想要封装非唯一标签的东西,一个可以是任何可比较对象的值以及成为首选选项的概念时,我想到了以下协议:

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)
    }
}

Now I want to implement the protocol in a generic struct and I cant figure out how. 现在,我想以通用结构实现该协议,但我不知道该怎么做。 What I want to do is 我想做的是

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

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

Any pointer would be helpful 任何指针都会有所帮助

The answer was pretty simple. 答案很简单。 I needed to constraint Key and Value in the struct. 我需要在结构中约束键和值。 The following struct compiles as expected 以下结构按预期编译

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM