【问题标题】:Convert a Swift Property Observer Into ObjC将 Swift 属性观察器转换为 ObjC
【发布时间】:2019-07-31 21:09:59
【问题描述】:
这段 ObjC 代码和 Swift 的结果一样吗?
var bottomColor = UIColor.gray {
didSet {
self.updateColors()
}
}
对
- (void)setBottomColor:(UIColor *)bottomColor
{
bottomColor = [[UIColor grayColor];
if (_bottomColor != bottomColor) {
_bottomColor = bottomColor;
[self updateColors];
}
}
如果没有,我该如何正确翻译 Swift?
【问题讨论】:
标签:
ios
objective-c
swift
properties
【解决方案1】:
这两个代码不一样。
在 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 应在init 中设置为[UIColor gray]。
【解决方案2】:
不!
在 swift 代码中,bottomColor 是一个以gray 启动的变量,并且每次它发生变化(为其设置另一种颜色)都会触发updateColors,但在objective-c 代码中,该方法只会触发updateColors if参数不等于[UIColor grayColor]
编辑:
你可以通过这种方式在objective-c中实现swift代码:
• 覆盖设置器并自己实现设置器。
• 在init 中设置bottomColor = [UIColor grayColor]。
- (void)setBottomColor:(UIColor *)bottomColor
{
_bottomColor = bottomColor;
[self updateColors];
}