Reputation: 8718
Referencing:
We have:
class SomeBaseClass {
class func printClassName() {
print("SomeBaseClass")
}
}
class SomeSubClass: SomeBaseClass {
override class func printClassName() {
print("SomeSubClass")
}
}
let someInstance: SomeBaseClass = SomeSubClass()
// The compile-time type of someInstance is SomeBaseClass,
// and the runtime type of someInstance is SomeBaseClass
someInstance.dynamicType.printClassName()
// prints "SomeSubClass"
Use the identity operators (=== and !==) to test whether an instance’s runtime type is the same as its compile-time type.
if someInstance.dynamicType === someInstance.self {
print("The dynamic type of someInstance is SomeBaseCass")
}
else {
print("The dynamic type of someInstance isn't SomeBaseClass")
}
but someInstance.self
appears to refer to the object, not the object's compile-time type, as claimed by the documentation. In fact in Xcode 7.2, the test does not evaluate to true even when we initialize someInstance
as SomeBaseClass
.
It does not inspire confidence that the docs have a typo (SomeBaseCass).
The only way I can find to make the "true" clause fire is the mutation:
if someInstance.dynamicType == SomeBaseClass.self { ... }
which is interesting but misses the fully dynamic run-time type-checking capability that the flawed Apple docs are trying to show.
Who's wrong and how to resolve?
Upvotes: 0
Views: 127
Reputation: 11
i have doubts about
let someInstance: SomeBaseClass = SomeSubClass()
// The compile-time type of someInstance is SomeBaseClass,
// and the runtime type of someInstance is SomeBaseClass
someInstance.dynamicType.printClassName()
// prints "SomeSubClass"
and the runtime type of someInstance should BE [SomeSubClass],
Upvotes: 0
Reputation: 46
It’s a typo — kudos to you. That section is about Metatype type and they use type_name.self throughout the section except that very line.
Other than that dynamicType works as advertised — nothing wrong here.
Upvotes: 1