Reputation: 33
I have an issue with Swift class function inheritance, here is a example of the code:
class A {
class func getName() -> String {
return "I'm class A"
}
func print() -> Void {
println(A.getName())
}
}
class B : A {
override class func getName() -> String {
return "I'm class B"
}
}
var b = B()
b.print() //This line prints out "I'm class A"
The last line prints out "I'm class A", my intension is to print out "I'm class B", because the instance type is class B. How should I change the code in class A function "print()" to let the class A realize the instance type is B and prints out "I'm class B"? If I remove the "class" prefix tot he function "getName()", then it would do what I asked for, but how to do the same with the class function?
Upvotes: 3
Views: 449
Reputation: 27984
Use dynamicType
.
class A {
func print() -> Void {
println(self.dynamicType.getName())
}
}
The example in the Swift Language Reference is similar to yours, incidentally.
Upvotes: 1