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.
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.