[英]Property encapsulation with property observer - Swift
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 . 如果userName
为空,则需要将username设置为Unknown 。 I am checking this condition in willSet
but unfortunately it unable to set the value as self.userName = "Unknown"
. 我正在willSet
检查此条件,但是很遗憾,它无法将值设置为self.userName = "Unknown"
。
If I do same with getter-setter
then it can be achievable with extra private param. 如果我对getter-setter
进行同样的操作,那么可以通过额外的私有参数来实现。 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 示例代码-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?? 问:如何使用willSet实现这种封装? If I somewhere misconcepted then please correct me. 如果我在某个地方误解了,请纠正我。
Thanks 谢谢
Just reset in didSet
: 只需在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. 但是请记住,不会从init
调用属性观察器,因此,如果有人let c = MyClass(name: "")
userName
仍然是空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.