简体   繁体   English

如何使使用 Callable (callAsFunction()) 的结构与协议一起工作?

[英]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.我试图在直接使用protocoldependency 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.

相关问题 如何使结构符合自定义协议? - How to make struct to conform a custom protocol? 如何使一个结构符合一个具有属性的协议符合swift 4中的另一个协议? - How to make a struct conforms to a protocol which has a property conforms to another protocol in swift 4? 我该如何制定一个通用协议,使我能够在任何有意义的结构或类中实现“ add”方法? - How do I make a generic protocol that enables me to implement an `add` method in any struct or class it makes sense? 使使用swift协议作为参数的客观C方法可公开访问 - Make a objective C method that uses a swift protocol as parameter public accesable 如何在struct中实现此协议 - How do I implement this protocol in struct 如何在Struct中实现协议可选方法? - How to implement protocol optional method in Struct? 如何断言结构符合协议? - How can I assert a struct conforms to a protocol? 如何制作一个声明协议类型属性的协议? - How to make a protocol that declares a property of a protocol type? 如何使协议符合 Swift 中的另一个协议? - how to make protocol to conform another protocol in Swift? 我可以多次使结构或类符合通用协议吗? - Can I make a struct or class conform to a generic protocol multiple times?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM