Swift: check if generic type conforms to protocol

前端 未结 8 1439
[愿得一人]
[愿得一人] 2020-12-07 17:24

I have a protocol that I defined like so:

protocol MyProtocol {
   ...
}

I also have a generic struct:

struct MyStruct <         


        
相关标签:
8条回答
  • 2020-12-07 18:09

    You need declare protocol as @objc:

    @objc protocol MyProtocol {
        ...
    } 
    

    From Apple's "The Swift Programming Language" book:

    You can check for protocol conformance only if your protocol is marked with the @objc attribute, as seen for the HasArea protocol above. This attribute indicates that the protocol should be exposed to Objective-C code and is described in Using Swift with Cocoa and Objective-C. Even if you are not interoperating with Objective-C, you need to mark your protocols with the @objc attribute if you want to be able to check for protocol conformance.

    Note also that @objc protocols can be adopted only by classes, and not by structures or enumerations. If you mark your protocol as @objc in order to check for conformance, you will be able to apply that protocol only to class types.

    0 讨论(0)
  • 2020-12-07 18:12

    A bit late but you can test if something responds to protocol with as ? test:

    if let currentVC = myViewController as? MyCustomProtocol {
        // currentVC responds to the MyCustomProtocol protocol =]
    }
    

    EDIT: a bit shorter:

    if let _ = self as? MyProtocol {
        // match
    }
    

    And using a guard:

    guard let _ = self as? MyProtocol else {
        // doesn't match
        return
    }
    
    0 讨论(0)
提交回复
热议问题