是否可以允许在 Swift 初始化期间调用 didSet? [英] Is it possible to allow didSet to be called during initialization in Swift?
问题描述
问题
Apple 的文档 指定:
<块引用>willSet 和 didSet 观察者在属性第一次初始化时不会被调用.仅当属性的值设置在初始化上下文之外时才会调用它们.
是否可以在初始化期间强制调用这些?
为什么?
假设我有这门课
class SomeClass {var someProperty: AnyObject {已设置{做东西()}}init(someProperty: AnyObject) {self.someProperty = someProperty做东西()}func doStuff() {//既然设置了 someProperty 就做一些事情}}
我创建了方法 doStuff
,以使处理调用更加简洁,但我宁愿只处理 didSet
函数中的属性.有没有办法在初始化期间强制调用它?
更新
我决定为我的类移除便利的初始化器,并强制您在初始化后设置该属性.这让我知道 didSet
将始终被调用.我还没有决定这是否总体上更好,但它很适合我的情况.
创建自己的 set-Method 并在您的 init-Method 中使用它:
class SomeClass {var someProperty: AnyObject!{已设置{//做一些事情}}init(someProperty: AnyObject) {setSomeProperty(someProperty)}func setSomeProperty(newValue:AnyObject) {self.someProperty = newValue}}
<块引用>
通过将 someProperty
声明为类型:AnyObject!
(一个隐式的解包可选),您允许 self 完全初始化而无需someProperty
正在设置.你打电话时setSomeProperty(someProperty)
你正在调用相当于self.setSomeProperty(someProperty)
.通常你不能这样做是因为 self 尚未完全初始化.自从someProperty
不需要初始化,您正在调用方法依赖于 self,Swift 离开初始化上下文并didSet 将运行.
Question
Apple's docs specify that:
willSet and didSet observers are not called when a property is first initialized. They are only called when the property’s value is set outside of an initialization context.
Is it possible to force these to be called during initialization?
Why?
Let's say I have this class
class SomeClass {
var someProperty: AnyObject {
didSet {
doStuff()
}
}
init(someProperty: AnyObject) {
self.someProperty = someProperty
doStuff()
}
func doStuff() {
// do stuff now that someProperty is set
}
}
I created the method doStuff
, to make the processing calls more concise, but I'd rather just process the property within the didSet
function. Is there a way to force this to call during initialization?
Update
I decided to just remove the convenience intializer for my class and force you to set the property after initialization. This allows me to know didSet
will always be called. I haven't decided if this is better overall, but it suits my situation well.
Create an own set-Method and use it within your init-Method:
class SomeClass {
var someProperty: AnyObject! {
didSet {
//do some Stuff
}
}
init(someProperty: AnyObject) {
setSomeProperty(someProperty)
}
func setSomeProperty(newValue:AnyObject) {
self.someProperty = newValue
}
}
By declaring
someProperty
as type:AnyObject!
(an implicitly unwrapped optional), you allow self to fully initialize withoutsomeProperty
being set. When you callsetSomeProperty(someProperty)
you're calling an equivalent ofself.setSomeProperty(someProperty)
. Normally you wouldn't be able to do this because self hasn't been fully initialized. SincesomeProperty
doesn't require initialization and you are calling a method dependent on self, Swift leaves the initialization context and didSet will run.
这篇关于是否可以允许在 Swift 初始化期间调用 didSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!