Swift: check if generic type conforms to protocol

前端 未结 8 1512
[愿得一人]
[愿得一人] 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: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
    }
    

提交回复
热议问题