Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding didSet

I want to override the property observer and calling the "super.didSet". Is that possible?

class Foo {
    var name: String = "" { didSet { print("name has been set") } }
}

class Bar: Foo {
    override var name: String = "" { 
        didSet { 
            print("print this first")
            // print the line set in the superclass
        }
    }
}
like image 503
Henny Lee Avatar asked Feb 01 '16 10:02

Henny Lee


1 Answers

I have tried your code in a playground and got and error

Variable with getter/ setter cannot have and initial value.

So I just removed ="" from the orverriding variable. like below:

class Foo {
    var name: String = "" { didSet { print("name has been set") } }
}

class Bar: Foo {
    override var name: String  {
        didSet {
            print("print this first")
            // print the line set in the superclass
        }
    }
}

let bar = Bar()
bar.name = "name"

and that's what I got in consol:

name has been set
print this first
like image 79
Ismail Avatar answered Sep 23 '22 10:09

Ismail