Home > OS >  Swift: Should I Use `self` in ViewController Methods in Swift/iOS?
Swift: Should I Use `self` in ViewController Methods in Swift/iOS?

Time:01-20

There are two way to call variables & methods in ViewController:

Case 1: Using self

import UIKit

class ViewController: UIViewController {
    var count = 0;
    override func viewDidLoad() {
        super.viewDidLoad()
        self.count = 1
        self.myFunc()
    }

    func myFunc(){
       ...
    }
}

Case 2: Access directly

import UIKit

class ViewController: UIViewController {
    var count = 0;
    override func viewDidLoad() {
        super.viewDidLoad()
        count = 1
        myFunc()
    }
    func myFunc(){
       ...
    }
}

Should I call variables and methods with the instance `self` in the scalable project at everywhere, or access them directly, as calling with the instance is a good way?

There is any difference between those two a function-calls in a class:

self.myFunc()

VS

myFunc()

It is working in both ways. It make any difference?

CodePudding user response:

The best practice would be that we should avoid unnecessary calls with self.

  • It should be used when it's necessary like you want have a initialiser or a function with same name as your variable then you can use self to distinguish between both.
  • Another place would be the clousure.
  • Related