【发布时间】:2014-06-14 00:47:18
【问题描述】:
在这样一个简单的例子中,我可以省略 self 来引用 backgroundLayer,因为 backgroundColor 设置在哪个 backgroundLayer 上是明确的。
class SpecialView: UIView {
let backgroundLayer = CAShapeLayer()
init() {
backgroundLayer.backgroundColor = UIColor.greenColor().CGColor
}
}
但是,就像在 Objective-C 中一样,我们可以通过添加类似命名的局部变量(或常量)来混淆事物。现在在非形状图层上设置了背景颜色:
class SpecialView: UIView {
let backgroundLayer = CAShapeLayer()
init() {
var backgroundLayer = CALayer()
backgroundLayer.backgroundColor = UIColor.greenColor().CGColor
}
}
(通过 self.backgroundLayer.backgroundColor 解决)
在 Objective-C 中,我总是避免使用 ivars 来获取属性,并且为了清楚起见,属性总是以 self 为前缀。我不必担心 swift 中的 ivars,但是对于何时应该在 swift 中使用 self 是否还有其他注意事项?
【问题讨论】:
-
考虑接受解决方案。
标签: swift