When should I access properties with self in swift?

swift self
swift static property
swift mutating
swift static function
swift class
swift static class
what is a method in swift
static swift

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 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:

  1. That is an instant and obvious sign that the variable is a property. This is important because it being a property means that its state can vary more widely and in different ways than a local variable. Also, changing a property has larger implications than changing a local variable.
  2. The code does not need to be updated if you decide to introduce a parameter or variable with the same name as the property
  3. Code can be easily copied in and out of closures that do require self

How to Use Correctly 'self' Keyword in Swift, for property access in closures. But if you use self. everywhere, you won't even notice when a closure also uses self. and you could fall prey  In addition to properties, you can use instance variables as a backing store for the values stored in a property. Swift unifies these concepts into a single property declaration. A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly.

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.

Clean code: when to use "self." in Swift, and when not to, to indicate that a method is a type method. Type methods contrast with instance methods, in that: Instance methods are called on an individual instance of one unique/chosen type. Type methods are called on the actual type, in and of itself. Access Levels¶ Swift provides five different access levels for entities within your code. These access levels are relative to the source file in which an entity is defined, and also relative to the module that source file belongs to.

Looking at Ray Wenderlich's style guide

Use of Self

For conciseness, avoid using self since Swift does not require it to access an object's properties or invoke its methods.

Use self only when required by the compiler (in @escaping closures, or in initializers to disambiguate properties from arguments). In other words, if it compiles without self then omit it.

Swift documentation makes the same recommendation.

The self Property

Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods.

The increment() method in the example above could have been written like this:

func increment() {
    self.count += 1
}

In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use of count (rather than self.count) inside the three instance methods for Counter.

The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name.

Here, self disambiguates between a method parameter called x and an instance property that is also called x:

struct Point {
    var x = 0.0, y = 0.0

    func isToTheRightOf(x: Double) -> Bool {
        return self.x > x
    }
}

let somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOf(x: 1.0) {
    print("This point is to the right of the line where x == 1.0")
}

// Prints "This point is to the right of the line where x == 1.0"

All about Properties in swift - Abhimuralidharan, The fact that structures and enumerations can define methods in Swift is a major of those instances, either by providing ways to access and modify instance properties, You use the self property to refer to the current instance within its own  One example of when to use lazy initialization is when the initial value for a property is not known until after the object is initialized. For example, if you have a Person class and a personalizedGreeting property. The personalizedGreeting property can be lazily instantiated after the object is created so it can contain the name of the person. Here’s a quick example:

As Apple documentation says in https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html

The self Property

Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods.

The increment() method in the example above could have been written like this:

func increment() {
    self.count += 1
}

In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use of count (rather than self.count) inside the three instance methods for Counter.

The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name.

Here, self disambiguates between a method parameter called x and an instance property that is also called x:

struct Point {
    var x = 0.0, y = 0.0
    func isToTheRightOf(x: Double) -> Bool {
        return self.x > x
    }
}
let somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOf(x: 1.0) {
    print("This point is to the right of the line where x == 1.0")
}
// Prints "This point is to the right of the line where x == 1.0"

Without the self prefix, Swift would assume that both uses of x referred to the method parameter called x.

I would prefer to keep using self whenever I'm using a property to omit these misunderstandings.

Static vs Class vs Global Functions in Swift, Property observers can be added to stored properties you define yourself, and the purpose of this DataManager class is to manage and provide access to this  Property Requirements¶. A protocol can require any conforming type to provide an instance property or type property with a particular name and type. The protocol doesn’t specify whether the property should be a stored property or a computed property—it only specifies the required property name and type.

What does "static" mean in Swift?, You use the self property to refer to the current instance within its own instance methods. I'll create a class that represents a geometric point on a  If you use an extension to add an initializer to a structure that was declared in another module, the new initializer can’t access self until it calls an initializer from the defining module. The example below defines a custom Rect structure to represent a geometric rectangle.

Methods, Swift. What is a lazy stored property in Swift? How and when should during initialization so you cannot use self to access any properties or  Structures and Classes¶. Structures and classes are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions.

Properties, That is also correct, as type(of) transforms something an object into something that allows you to access all class properties. But have you ever  SWIFT's Customer Security Programme – a focused effort to help customers reinforce the security of their SWIFT-related infrastructure against cyber-threats. Discover all our latest press releases and materials for journalist & influencers. Discover our press corner. Get personalised insights. straight to your inbox Sign up now.

Self versus self in Swift 4 – capital “S” and lowercase “s” – iOS Brain, Being able to pass an instance of the current object to others;; Accessing special properties that are otherwise unavailable, such as reflective property this.class in​  Swift - Classes - Classes in Swift 4 are building blocks of flexible constructs. Similar to constants, variables and functions the user can define class properties and methods.

Comments
  • Consider accepting a solution.
  • Yes and yes. Sometimes brevity and clarity are at odds - always use self and you won't get stung by a rare case of overlap.
  • @NateCook I actually filed a bug with Apple about making self required and I encourage you to do the same if you agree :)
  • The reason I like not using self is that when closure capture forces you to use self, it then stands out (which is good, because referencing self in a closure retains it, unlike other contexts, so you want it to look "different")
  • I reckon not using self keeps the code concise and clear. This is especially true when you are writing out formulas using the properties. And thanks to Xcode 7's syntax colouring it's very clear which variables are local and which ones are properties.
  • I agree on all points. To a degree this comes down to personal design taste, but clarity is better than brevity most of the time.
  • Can you cite the relevant part of Apple's documentation? I cannot find a recommendation.
  • @Apfelsaft I've updated my answer. The relevant recommendation is under the section The Self Property. Swift documentation states "In practice, you don’t need to write self in your code very often."
  • It's not a recommendation, It just an explanation about the self reference with a big BUT detailing some particular cases where you must use self. Do not translate a personal interpretation to a recommendation. I prefer to use it only in one way (Always use self) and not to have ambiguity on my code, but again: It's my preference.