Search code examples
iosswiftself

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


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?


Solution

  • 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
    }