Is there a tangible benefit to using "self" outside of closures?
Asked Answered
L

4

7

I have noticed a few people in the industry will use the self keyword even when not explicitly required (i.e. outside of closures).

Example:

import UIKit
import MapView
import CoreLocation

class viewController: UIViewController, MKMapViewDelegate, CLLocationDelegate {

    let mapView = MKMapView()
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mapView.delegate = self
        self.mapView.showsUserLocation = true

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }
}

Is there a tangible benefit to this, runtime-wise? Or is this purely a stylistic choice?

Lebron answered 8/10, 2018 at 23:2 Comment(4)
Stylistic choice that comes from ObjectiveC where this was necessary.Foreshore
As you've coded? Not really. But if your init (or other function) takes a named input parameter (say in your code, desiredAccuracy), sure. It's self documenting code. PLEASE NOTE: Many will disagree with this, as it's not "Swifty". And... thinking it through, I guess everything I just stated is stylistic.Inexplicit
I do it because for a couple of reasons; Habit from Objective-C and also it shows me (and anyone else that looks at my code) that I am accessing a property, not a local variable; ie. this action may have consequences (or be influenced by events) outside of the current context. It can also be required for disambiguation where there is both a property and a local variable with the same nameGlucose
it is the same as this in Java and self in Objective-C, but with Swift, self is only require when you call a property or method from a closure or to differentiate property names inside your code. So you can use almost all of your class components safely without using self unless you are making the call from a closure.Demitasse
A
12

There is.

In the examples you provided it makes no difference, it's purely a style choice. Some people might like it since it explicitly tells you you're modifying self, personally I think it looks cleaner without.

Where it matters is when you have a local variable with the same name. Let's say you have a class that has a var count: Int property. Then, in one of your methods, you declare a new variable with the same name.

The local variable will be used whenever you type count, so if you want to modify or read the object's variable, you'll need to use self.

Some examples where it makes a difference:

guard let count = calculateCount() as? Int else { return }
self.count = count

init(count: Int) {
  self.count = count
}

func updateCount(_ count: Int) {
  self.count = count
}
Asir answered 8/10, 2018 at 23:16 Comment(0)
P
4

Yes there are some benefits.

  • Using keywords like self or init or Swift prevent Xcode from ambiguity of overloads
  • make it compile faster
  • brings autocomplete suggestions faster;

that's it! Even though you use them explicitly, the compiler removes them from compiled code for compressing reasons. But it is not preferred! It's all about the scope of variables and functions.

Take a look at this example:

let name = "global variable"
class MyClass {
    let name = "object variable"

    func testScopes() {
        let name = "function local variable"
        print(name) //prints: function local variable
        print(self.name) //prints: object variable
        print(MyProject.name) // prints: global variable
    }
}

let myObject = MyClass()
myObject.testScopes()

Here are three variables with three different valid scopes. You can refer to each one you need differently. Swift community suggested:

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.

But it's ultimately up to you and your company's code style guide.

Prunelle answered 14/10, 2018 at 13:6 Comment(0)
G
1

Aside from the practical reason where it is required when there is a local variable or parameter with the same name, I do it because for a couple of reasons:

  • Habit from Objective-C

  • It explicitly shows me (and anyone else that looks at my code) that I am accessing a property, not a local variable; ie. this action may have consequences (or be influenced by events) outside of the current context.

Glucose answered 8/10, 2018 at 23:28 Comment(2)
A note regarding the second bullet - clear code doesn't need self, one should be able to tell from the context if it's dealing with a property or a local var (i.e. clear naming).Cattegat
Naming wont help a lot but the same thing self. is doing for you can be just setup in Xcode as a different font or color.Foreshore
T
0

My personal convention is to only use self in closures. For a few reasons.

  1. It tells me, as a developer, that we are explicitly in a closure, because self is required.
  2. self is very important in closures, and lets us know of possible retain cycles and memory leaks when we capture self strongly.
  3. It is redundant when not in a closure, when there are not multiple variables of the same name inside the same or different scopes.

One thing I will say, when coding, using self. is a quick way to see what's available in the class or struct we are in. However, I will remove it after I find what I need.

Trapeze answered 13/10, 2018 at 19:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.