【问题标题】:generics struct implementing protocol with associated type具有关联类型的泛型结构实现协议
【发布时间】:2017-10-20 07:25:18
【问题描述】:

我在为我的 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&lt;Key, Value&gt;' does not conform to protocol 'OptionProtocol'

任何指针都会有帮助

【问题讨论】:

    标签: swift struct swift-protocols


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      相关资源
      最近更新 更多