I am trying to do property encapsulation with property observer. Refer below Sample Code. If userName
is empty then need to set username as Unknown . I am checking this condition in willSet
but unfortunately it unable to set the value as self.userName = "Unknown"
.
If I do same with getter-setter
then it can be achievable with extra private param. Check Below code.
With get-set
private var userName : String
var name : String {
get {
return self.userName
}
set {
if newValue.isEmpty {
self.userName = "Unknown"
}
}
}
Sample Code - WillSet
class MyClass {
var userName : String {
willSet{
print("Will set called")
if newValue.isEmpty {
print("If condi \(newValue) ..")
self.userName = "Unknown"
}
}
didSet {
print("Did set called")
}
}
init(name : String) {
self.userName = name
}
}
let c = MyClass(name: "Hello")
c.userName = ""
print("var ->", c.userName)
Output:
Q: How to achieve this encapsulation with willSet?? If I somewhere misconcepted then please correct me.
Thanks
Just reset in didSet
:
class MyClass {
var userName : String {
didSet {
if userName.isEmpty {
self.userName = "Unknown"
}
}
}
init(name : String) {
self.userName = name
}
}
But keep in mind that property observers are not called from init
so if someone does let c = MyClass(name: "")
then userName
will still be the empty string.
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.