When should I access properties with self in swift?

后端 未结 6 2028
一生所求
一生所求 2020-11-27 04:38

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



        
6条回答
  •  长情又很酷
    2020-11-27 05:20

    Most of the time we can skip self. when we access class properties.

    1. However there is one time when we MUST use it: when we try to set self.property in a closure:

      dispatch_async(dispatch_get_main_queue(), {
          // we cannot assign to properties of self
          self.view = nil 
      
          // but can access properties
          someFunc(view)
      })
      
    2. one time when we SHOULD use it: so you don't mess a local variable with class property:

      class MyClass {
          var someVar: String = "class prop"
      
          func setProperty(someVar:String = "method attribute") -> () {
              print(self.someVar) // Output: class property
              print(someVar) // Output: method attribute
          }
      }
      
    3. other places where we CAN use self. before property just to be expressive about were variable/constant comes from.

提交回复
热议问题