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 } }
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 } }
(this is resolved by using self.backgroundLayer.backgroundColor)
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?
The self keyword is usually not required. The only times you should use self is: To differentiate a property from a local variable that has the same name.
You use self when: Defining an instance method. It is passed automatically as the first parameter when you call a method on an instance, and it is the instance on which the method was called. Referencing a class or instance attribute from inside an instance method.
In Swift self is a special property of an instance that holds the instance itself. Most of the times self appears in an initializer or method of a class, structure or enumeration. The motto favor clarity over brevity is a valuable strategy to follow.
The difference is that self is used in types and instances of types to refer to the type that it's in; and Self is used in protocols and extensions where the actual type is not yet known. In even simpler terms, self is used within an existing type; Self is used to refer to a type that Self is not yet in.
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.
However, personally, I prefer to always write "self" because:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With