omerc
omerc

Reputation: 179

the using of self property

I'm kind new to the Swift language and I'm trying to understand the "self" methods property. I read about it at apple docs and as I understood the using of self-property is when I want to "“refer to the current instance within its own instance methods”. as I read it and the example of apple I understood the using and the reason for it but after that as I look at some tutorial I understood that I didn't really get it. I adding the code of the tutorial and maybe someone can explain me the using according to the code.

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

let width: CGFloat = 240.0
let height: CGFloat = 160.0

let demoView = DemoView(frame: CGRect(x: self.view.frame.size.width/2 - width/2,
                                      y: self.view.frame.size.height/2 - height/2,
                                      width: width,
                                      height: height))

self.view.addSubview(demoView)
}

I really don't get the using of self-property in here, especially because I don't see any "same name" var outside the function. hope someone can help me understand it better. thanks.

Upvotes: 1

Views: 90

Answers (1)

Connor Neville
Connor Neville

Reputation: 7351

You are correct that, in this case, there is no same-name variable outside the scope, so in this case, there's no need to use self. Let's look at an example where there would be a difference.

class MyClass {

    let myInteger = 6
    let myBool = false

    func doSomething(_ myInteger: Int) {
        print(myInteger, self.myInteger)
    }

}

Then, anywhere else in your code:

let object = MyClass()
object.doSomething(4) // this prints "4, 6" because `myInteger` refers
                      // to the parameter (4), and `self.myInteger`
                      // refers to self's property (6)

Upvotes: 1

Related Questions