Swift - 属性上的自定义设置器 [英] Swift - Custom setter on property

查看:58
本文介绍了Swift - 属性上的自定义设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将项目转换为 Swift 代码,但在 setter 中遇到了问题.我的 Objective-C 代码如下所示:

I am converting a project in to Swift code and have come across an issue in a setter. My Objective-C code looked like this:

- (void)setDocument:(MyDocument *)document
{
    if (![_document isEqual:document]) {
        _document = document;

        [self useDocument];
    }
}

并允许我的视图控制器在每次设置文档时运行它(通常在呈现视图控制器的 prepareForSegue: 方法中).

and allowed my View Controller to run this each time the document was set (typically in the prepareForSegue: method of the presenting View Controller).

我发现了属性观察器 willSetdidSet 但它们只在属性更新时起作用,而不是在初始化和更新时起作用.

I have found the property observers willSet and didSet but they only work when the property is being updated, not when it’s initialised and updated.

有什么想法吗?谢谢

更新

在尝试 get{} 和 set{} 后,我收到 EXC_BAD_ACCESS 错误

after trying get{} and set{} I get the EXC_BAD_ACCESS error

var document: UIDocument? {
    get {
        return self.document!
    }
    set {
        self.document = newValue

        useDocument()
    }
}

推荐答案

你不能这样使用 set 因为当你调用 self.document = newValue 时,你'再次调用setter;你创造了一个无限循环.

You can't use set like that because when you call self.document = newValue you're just calling the setter again; you've created an infinite loop.

你需要做的是创建一个单独的属性来实际存储值:

What you have to do instead is create a separate property to actually store the value in:

private var _document: UIDocument? = nil
var document: UIDocument? {
    get {
        return self._document
    }
    set {
        self._document = newValue
        useDocument()
    }
}

这篇关于Swift - 属性上的自定义设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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