Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift class function inheritance issue

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?

like image 550
Zhang Zhang Avatar asked May 03 '26 23:05

Zhang Zhang


1 Answers

Use dynamicType.

class A {
    func print() -> Void {
        println(self.dynamicType.getName())
    }
}

The example in the Swift Language Reference is similar to yours, incidentally.

like image 54
Kurt Revis Avatar answered May 05 '26 13:05

Kurt Revis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!