是否可以在Swift初始化期间允许调用didSet? [英] Is it possible to allow didSet to be called during initialization in Swift?

查看:81
本文介绍了是否可以在Swift初始化期间允许调用didSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple的文档指定:


首次初始化属性时,不会调用

willSet和didSet观察者。它们仅在属性的值设置在初始化上下文之外时才被调用。

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?

假设我有这个课程

class SomeClass {
    var someProperty: AnyObject {
        didSet {
            doStuff()
        }
    }

    init(someProperty: AnyObject) {
        self.someProperty = someProperty
        doStuff()
    }

    func doStuff() {
        // do stuff now that someProperty is set
    }
}

I创建方法 doStuff ,使处理调用更简洁,但我宁愿只处理 didSet 功能。有没有办法强制在初始化期间调用它?

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?

我决定只是删除方便我的类的intializer并强制您在初始化后设置属性。这让我知道 didSet 将永远被调用。我还没有决定整体是否更好,但它很适合我的情况。

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.

推荐答案

创建一个自己的set-Method并在init-Method中使用它:

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
    }
}

这篇关于是否可以在Swift初始化期间允许调用didSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆