GoodSp33d GoodSp33d - 4 months ago 13
iOS Question

Can we access overridden class function from the base class in swift?

Am stuck in a situation where I have a

let
variable declared & initialized in base class. I would need to pass a different enum in one of my other classes extending this base class.

So, I tried creating a class function in base class so that I can override and return a different enum type. But is there any way that I can access the extended class from base class ?

Created a sample code below to help explain:

class A {

var string: String {
get {
// Is it possible to refer to the class type dynamically here ?
// So that it would call B's printMessage
return A.printMessage("Hello")
}
}

class func printMessage(message: String) -> String {
return "You shall not pass !"
}

}


class B: A {

override class func printMessage(message:String) -> String {
return message + "World !"
}

}

let obj = B()
print(obj.string)

Answer

make it like this:

var string: String {
    get {
        // Is it possible to refer to the class type dynamically here ?
        // So that it would call B's printMessage
        return  self.dynamicType.printMessage("Hello")
    }
}
Comments