Swift: check if generic type conforms to protocol

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

    you can also leverage swift's switch case pattern matching, if you want to handle multiple cases of type T:

    func myFunc(s: MyStruct) -> T? {
        switch s {
        case let sType as MyProtocol:
            // do MyProtocol specific stuff here, using sType
        default:
            //this does not conform to MyProtocol
        ...
        }
    }
    

提交回复
热议问题