I have a protocol that I defined like so:
protocol MyProtocol { ... }
I also have a generic struct:
struct MyStruct <T> { ... }
Finally I have a generic function:
func myFunc <T> (s: MyStruct<T>) -> T? { ... }
I'd like to test inside of the function if the type T conforms to MyProtocol. Essentially I'd like to be able to do (~ pseudocode):
let conforms = T.self is MyProtocol
But this throws a compiler error:
error: cannot downcast from 'T.Type' to non-@objc protocol type 'MyProtocol' let conforms = T.self is MyProtocol ~~~~~~ ^ ~~~~~~~~~~
I have also tried variations, like T.self is MyProtocol.self
, T is MyProtocol
, and using ==
instead of is
. So far I haven't gotten anywhere. Any ideas?
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.
An associated type gives a placeholder name to a type that's used as part of the protocol. The actual type to use for that associated type isn't specified until the protocol is adopted. Associated types are specified with the associatedtype keyword.
Generic Protocols are for procedures/techniques involving human participants that are used on a regular basis, and which form all or part of subsequent research projects or taught modules.
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 }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With