我正在尝试使用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'.
我错过了什么吗?有什么办法可以实现吗?
谢谢.
您无法在协议本身上调用该方法,您必须在实现协议的类型上调用它.这不会改变,因为扩展中存在协议的默认实现.将您的类型更改Proto为ProtoDefaultImpl,它将按预期工作.
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 = ProtoDefaultImpl.create()
let output = instance.someMethod()
print(output)
Run Code Online (Sandbox Code Playgroud)
这输出: doing something
| 归档时间: |
|
| 查看次数: |
935 次 |
| 最近记录: |