I want to implement some NSNotificationCenter selector method in protocol extension. The reason is extensibility some mechanism for few ViewControllers. But this doesn't work. I have error: unrecognized selector.
Ok, I make some test like this:
protocol SomeProtocol{
func xyz()->Void
}
class BigData : NSObject, SomeProtocol{
func xyz() {
/
}
}
let big = BigData()
big.respondsToSelector("xyz")
It works fine - respondsToSelector() returns true, but if I write the code in protocol extension:
extension SomeProtocol{
func xyz(){
}
}
then respondsToSelector() return false. My question is: why? How can I fix this? I really need this mechanism.
I think you have probably found a bug. I would expect it to work. It might be a bug that is a fring case, using Objective-C RTTI within Swift, and therefore it might not be a high priority fix 😟.
Can you use this as a work around?
protocol ABCProtocol {
func abc() -> String
}
protocol XYZABCProtocol: ABCProtocol {
func xyz() -> String
}
class BigData: XYZABCProtocol {
func xyz() -> String {
return "XYZABC"
}
func abc() -> String {
return "ABC"
}
}
func test(abc: ABCProtocol) -> String {
if let xyzabc = abc as? XYZABCProtocol {
return xyzabc.xyz()
} else {
return abc.abc()
}
}
let big = BigData()
test(big) // XYZABC