扩展协议以提供对“可比较”协议的默认合规性

时间:2017-01-14 23:54:33

标签: swift swift3 protocols

对于我声明的协议,我希望有let req = require("somewhere"); // my javascript object function myfunction(request : Request) { // some code } myfunction(req);// ok myfunction(20);// Error how can I create the Request type 的默认实现。以下是错误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()
    }
}

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

我不希望每个资产都从公共基类继承(因为这会破坏协议的目的......)

Swift 3中是否尚未支持协议的协议扩展(类似于类)?

1 个答案:

答案 0 :(得分:2)

您的协议必须在其主声明中继承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()
    }
}