Derived class does not conform to protocol
import Foundation
import Swift
struct HasType<Type: AnyObject> {
static func inObject<T>(object: T) -> Bool {
return object is Type
}
}
@objc protocol MyBaseProtocol : class {}
@objc protocol MyDerivedProtocol : MyBaseProtocol {}
@objc class MyBaseClass : MyDerivedProtocol {}
@objc class MyDerivedClass : MyBaseClass {}
let mbc = MyBaseClass()
let mdc = MyDerivedClass()
HasType<MyBaseProtocol>.inObject(mbc) // True
HasType<MyDerivedProtocol>.inObject(mbc) // True
HasType<MyBaseProtocol>.inObject(mdc) // False
HasType<MyDerivedProtocol>.inObject(mdc) // False
HasType<MyBaseClass>.inObject(mdc) // True
HasType<MyDerivedClass>.inObject(mdc) // True
Why do these methods return 2 False. I expect everything to be true. What did I miss? All this code can be pasted on the playground
source to share
Seems like a bug. The problem can be simplified as:
@objc protocol MyProtocol {}
class MyBaseClass : MyProtocol {}
class MyDerivedClass : MyBaseClass {}
let mbc:AnyObject = MyBaseClass()
let mdc:AnyObject = MyDerivedClass()
mbc is MyProtocol // -> true
mdc is MyProtocol // -> false
A workaround is to make it MyBaseClass
inheritable fromNSObject
class MyBaseClass : NSObject, MyProtocol { }
^^^^^^^^^^
source to share
This is definitely a mistake. Another workaround I found is to force MyDerivedClass to obey MyDeriveProtocol.class MyDerivedClass : MyBaseClass, MyDerivedProtocol {}
import UIKit
import Foundation
struct HasType<Type: AnyObject> {
static func inObject<T>(object: T) -> Bool {
return object is Type
}
}
@objc protocol MyBaseProtocol {
func someValue() -> Double
}
@objc protocol MyDerivedProtocol : MyBaseProtocol{}
@objc class MyBaseClass : MyDerivedProtocol {
func someValue() -> Double { return 9.9 }
}
@objc class MyDerivedClass : MyBaseClass, MyDerivedProtocol {}
let mbc = MyBaseClass()
let mdc = MyDerivedClass()
mdc.someValue()
HasType<MyBaseProtocol>.inObject(mbc) // True
HasType<MyDerivedProtocol>.inObject(mbc) // True
HasType<MyBaseProtocol>.inObject(mdc) // true
HasType<MyDerivedProtocol>.inObject(mdc) // true
HasType<MyBaseClass>.inObject(mdc) // True
HasType<MyDerivedClass>.inObject(mdc) // True
Please note that you will not need to override methods and requirements MyDerivedProtocol
, as this has already been taken care of MyBaseClass
. It seems like a roundabout way of doing things.
source to share