将Swift属性观察器转换为ObjC

时间:2019-03-10 10:43:42

标签: ios objective-c swift properties

这段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?

2 个答案:

答案 0 :(得分:3)

两个代码不同。

在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];
}

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

答案 1 :(得分:0)

不!

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


编辑:

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

•覆盖设置器并自己实现设置器。
•将[UIColor grayColor]设置为init。

bottomColor = [UIColor grayColor]