Jef Roosens Jef Roosens - 5 months ago 18
Swift Question

Swift: Computed Properties Using Same Getters And/Or Setters

Everyone. I was wondering if it was possible in Swift to use the same property observers for multiple variables, without having to re-write them every time?

For example in this piece of Swift code below:

class Foo {
func setInfo() {
//Do Something
}

var var1 = "" {
didSet {
setInfo()
}
}

var var2 = "" {
didSet {
setInfo()
}
}

var var3 = "" {
didSet {
setInfo()
}
}
}


I have to write the same didSet-observer for every variable. Is there a way to write this shorter and without writing it over and over again?

Thanks in advance.

Answer

Write observers in one line if you wish (so do I in short constructions), it looks more readable. But there is generally no other way.

class Foo {

    var var1 = "" {didSet {setInfo()}}
    var var2 = "" {didSet {setInfo()}}
    var var3 = "" {didSet {setInfo()}}

    func setInfo() {
        //Do Something
    }
}
Comments