I have a protocol that I defined like so:
protocol MyProtocol {
...
}
I also have a generic struct:
struct MyStruct <
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.
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
}