我什么时候应该快速访问带有 self 的属性? [英] When should I access properties with self in swift?

查看:26
本文介绍了我什么时候应该快速访问带有 self 的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这样一个简单的例子中,我可以省略 self 来引用 backgroundLayer,因为 backgroundColor 设置在哪个 backgroundLayer 上是明确的.

In a simple example like this, I can omit self for referencing backgroundLayer because it's unambiguous which backgroundLayer the backgroundColor is set on.

class SpecialView: UIView {
    let backgroundLayer = CAShapeLayer()

    init() {
        backgroundLayer.backgroundColor = UIColor.greenColor().CGColor
    }
}

但是,就像在 Objective-C 中一样,我们可以通过添加类似命名的局部变量(或常量)来混淆事物.现在正在非形状图层上设置背景颜色:

But, just like in Objective-C, we can confuse things by adding local variables (or constants) named similarly. Now the backgroundColor is being set on the non-shape layer:

class SpecialView: UIView {
    let backgroundLayer = CAShapeLayer()

    init() {
        var backgroundLayer = CALayer()

        backgroundLayer.backgroundColor = UIColor.greenColor().CGColor
    }
}

(这是通过使用 self.backgroundLayer.backgroundColor 解决的)

(this is resolved by using self.backgroundLayer.backgroundColor)

在 Objective-C 中,我总是避开属性的 ivars,为了清楚起见,属性总是以 self 为前缀.我不必担心 swift 中的 ivars 但我应该在 swift 中何时使用 self 是否还有其他注意事项?

In Objective-C I always eschewed ivars for properties and properties were always prefixed with self for clarity. I don't have to worry about ivars in swift but are there other considerations for when I should use self in swift?

推荐答案

self 唯一需要的时候是在闭包内引用属性时同名的局部变量.

The only times self is required are when referencing a property inside a closure and, as you pointed out, to differentiate it from a local variable with the same name.

然而,就我个人而言,我更喜欢总是写self",因为:

However, personally, I prefer to always write "self" because:

  1. 这是变量是属性的即时且明显的标志.这很重要,因为它是一个属性意味着它的状态可以比局部变量更广泛地以不同的方式变化.此外,更改属性比更改局部变量具有更大的影响.
  2. 如果您决定引入与属性同名的参数或变量,则无需更新代码
  3. 代码可以很容易地复制进和复制出需要 self 的闭包

这篇关于我什么时候应该快速访问带有 self 的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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