相关疑难解决方法(0)

Swift:在协议扩展中提供默认协议实现

我正在尝试使用Swift,协议和协议扩展.具体来说,我试图在协议扩展中提供协议的默认实现.这是我的代码:

protocol Proto : class {
    func someMethod() -> String
}

extension Proto {
    static func create() -> Self {
        return ProtoDefaultImpl() as! Self
    }
}

class ProtoDefaultImpl : Proto {
    func someMethod() -> String {
        return "doing something"
    }
}

let instance = Proto.create()
let output = instance.someMethod()

print(output)
Run Code Online (Sandbox Code Playgroud)

编译器在我调用的行上抱怨Proto.create(),出现以下错误:error : static member 'create' cannot be used on instance of type 'Proto.Protocol'.

我错过了什么吗?有什么办法可以实现吗?

谢谢.

protocols swift

3
推荐指数
1
解决办法
935
查看次数

标签 统计

protocols ×1

swift ×1