[英]How to make a struct that uses Callable (callAsFunction()) works with protocol?
I'm trying to make the callAsFunction()
works when working directly with protocol
or dependency injection
, but it seems like the protocol instance
is not aware of the Callable
feature.我试图在直接使用
protocol
或dependency injection
时使callAsFunction()
工作,但protocol instance
似乎不知道Callable
功能。 I tried adding the func callAsFunction()
within the protocol decorating
, but it did not work too.我尝试在
protocol decorating
中添加func callAsFunction()
,但它也不起作用。 As you can see the sample code below, when creating an instance with the concrete struct, I'm able to work with the callAsFunction()
, but not with the protocol instance.正如您在下面的示例代码中看到的,在使用具体结构创建实例时,我可以使用
callAsFunction()
,但不能使用协议实例。
protocol Decorating {
//to implement
}
struct Decorate: Decorating {
func callAsFunction() {
print("Decorated!")
}
}
let decorate: Decorate = Decorate()
decorate() //worked
let decorate2: Decorating = Decorate()
decorate2() //failed
You can extend your protocol:你可以扩展你的协议:
protocol Decorating {
}
extension Decorating {
func callAsFunction() -> {
// Your code
}
}
Example of use:使用示例:
protocol Decorating {
var foo: Foo
}
extension Decorating {
func callAsFunction() -> {
foo.foo()
}
}
let decorate: Decorating = Decorate()
decorate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.