繁体   English   中英

将Swift属性观察器转换为ObjC

[英]Convert a Swift Property Observer Into ObjC

这段ObjC代码的结果与Swift相同吗?

var bottomColor = UIColor.gray {
    didSet {
        self.updateColors()
    }
}

VS

- (void)setBottomColor:(UIColor *)bottomColor
{
    bottomColor = [[UIColor grayColor];
    if (_bottomColor != bottomColor) {
        _bottomColor = bottomColor;
        [self updateColors];
    }
}

如果没有,如何正确翻译Swift?

这两个代码不相同。

在Swift中,只要设置了值,就会调用属性观察器。 新值是否等于旧值并不重要。 因此,这段代码将打印两次“ Hello”:

class A {
    var a: Int = 10 {
        didSet {
            print("Hello")
        }
    }
}

let a = A()
a.a = 10
a.a = 10

要将属性观察器转换为Objective-C,您无需检查值是否与以前相同,只需执行以下操作:

- (void)setBottomColor:(UIColor *)bottomColor
{
    _bottomColor = bottomColor;
    [self updateColors];
}

init中, bottomColor应该设置为[UIColor gray]

不!

在快速代码中,bottomColor是一个以gray开头的变量,每次更改时(为其设置其他颜色)都会触发updateColors但在Objective-C代码中,如果参数不等于[UIColor grayColor]则该方法只会触发updateColors


编辑:

您可以通过以下方式在Objective-C中实现快速代码:

•覆盖设置器并自己实施设置器。
•在init中设置bottomColor = [UIColor grayColor]

- (void)setBottomColor:(UIColor *)bottomColor
{
    _bottomColor = bottomColor;
    [self updateColors];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM