【问题标题】:Extending a protocol to provide default compliance to "Comparable" protocol扩展协议以提供对“可比较”协议的默认合规性
【发布时间】:2017-01-14 23:54:32
【问题描述】:

我希望为我声明的协议提供Comparable 的默认实现。以下给出错误Extension of protocol 'Asset' can not have an inheritance clause

protocol Asset {
    func getPriority() -> AssetPriority
}

extension Asset: Comparable {
    static func < (lhs: Asset, rhs: Asset) -> Bool {
        return lhs.getPriority() < rhs.getPriority()
    }
    static func == (lhs: Asset, rhs: Asset) -> Bool {
        return lhs.getPriority() == rhs.getPriority()
    }
}

我知道我可以进行协议继承(没有扩展):

protocol Asset: Comparable {
    func getPriority() -> AssetPriority
}

但是我必须一遍又一遍地实现相同的两个功能。

我不希望每个资产都继承自一个公共基类(因为这违背了协议的目的......)

在 Swift 3 中尚不支持协议的协议扩展(就像它用于类一样)?

【问题讨论】:

    标签: swift swift3 protocols


    【解决方案1】:

    您的协议必须在其主要声明中继承自 Comparable。然后,您可以在扩展中添加 Comparable 方法的默认实现。

    protocol Asset: Comparable {
        func getPriority() -> AssetPriority
    }
    
    extension Asset {
        static func < (lhs: Self, rhs: Self) -> Bool {
            return lhs.getPriority() < rhs.getPriority()
        }
        static func == (lhs: Self, rhs: Self) -> Bool {
            return lhs.getPriority() == rhs.getPriority()
        }
    }
    

    【讨论】:

    • @DudeOnRock 但是,如果你从EquatableComparable 继承,Asset 不能再用作它自己的类型。这是一个不完整的类型
    • 对不起,我判断你的答案太快了......我有Asset而不是Self作为扩展中的参数类型。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多