如何消除实现协议中静态方法的歧义?

时间:2015-10-12 17:51:12

标签: swift swift-protocols default-implementation

对于实例函数,\ n \ n \ n投射工作正常。

protocol Protocol1 {}
extension Protocol1 {
    func instanceFunc() {}
    static func staticFunc() {}
}

protocol Protocol2 {}
extension Protocol2 {
    func instanceFunc() {}
    static func staticFunc() {}
}

struct Struct: Protocol1, Protocol2 {
    func instanceFunc() {
        (self as Protocol1).instanceFunc()
        (self as Protocol2).instanceFunc()
    }

    static func staticFunc() {
        // My best guess. Nope!
        (Struct as Protocol1.Type).staticFunc()
        (Struct as Protocol2.Type).staticFunc()
    }
}

1 个答案:

答案 0 :(得分:1)

这应该做伎俩配偶

protocol Protocol1 {}
extension Protocol1 {
    func instanceFunc() {}
    static func staticFunc() {}
}

protocol Protocol2 {}
extension Protocol2 {
    func instanceFunc() {}
    static func staticFunc() {}
}

struct Struct: Protocol1, Protocol2 {
    func instanceFunc() {
        (self as Protocol1).instanceFunc()
        (self as Protocol2).instanceFunc()
    }

    static func staticFunc() {
        (Struct.self as Protocol1.Type).staticFunc()
        (Struct.self as Protocol2.Type).staticFunc()
    }
}