检查泛型类型是否符合协议

我有一个协议,我是这样定义的:

protocol MyProtocol {
...
}

我还有一个泛型结构:

struct MyStruct <T>  {
...
}

最后,我有一个通用函数:

func myFunc <T> (s: MyStruct<T>) -> T? {
...
}

我想在函数内部测试 T 类型是否符合 MyProtocol。本质上我希望能够做(~ 伪代码) :

let conforms = T.self is MyProtocol

但这会抛出一个编译器错误:

error: cannot downcast from 'T.Type' to non-@objc protocol type 'MyProtocol'
let conforms = T.self is MyProtocol
~~~~~~ ^  ~~~~~~~~~~

我也尝试了不同的变化,如 T.self is MyProtocol.selfT is MyProtocol,并使用 ==而不是 is。目前为止我还没有任何进展。有什么想法吗?

78070 次浏览

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.

The simplest answer is: don’t do that. Use overloading and constraints instead, and determine everything up-front at compile-time rather than testing stuff dynamically at runtime. Runtime type checking and compile-time generics are like steak and ice-cream – both are nice but mixing them is a bit weird.

Consider something like this:

protocol MyProtocol { }


struct MyStruct <T>  { let val: T }


func myFunc<T: MyProtocol>(s: MyStruct<T>) -> T? {
return s.val
}


func myFunc<T>(s: MyStruct<T>) -> T? {
return nil
}


struct S1: MyProtocol { }
struct S2 { }


let m1 = MyStruct(val: S1())
let m2 = MyStruct(val: S2())


myFunc(m1) // returns an instance of S1
myFunc(m2) // returns nil, because S2 doesn't implement MyProtocol

The downside being, you can’t establish dynamically if T supports a protocol at runtime:

let o: Any = S1()
let m3 = MyStruct(val: o)
myFunc(m3)  // will return nil even though o
// does actually implement MyProtocol

But, in all honesty, do you really need to do that inside your generic function? If you’re unsure what actual type something is, the better option may be to figure that out up-front rather than deferring it to later and prodding it inside a generic function to find out.

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
}

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

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

I have to say @Alex want to check if T type conforms to protocol rather than s. And some answerer didn't see clearly.

Check T type conforms to protocol like this :

if let _ = T.self as? MyProtocol.Type {
//  T conform MyProtocol
}

or

if T.self is MyProtocol.Type {
//  T conform MyProtocol
}

let conforms = T.self is MyProtocol.Type

A modern answer will be like this: (Swift 5.1)

func myFunc < T: MyProtocol> (s: MyStruct<T>) -> T? {    ... }

For test cases I check conformance like this:

let conforms: Bool = (Controller.self as Any) is Protocol.Type