BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Confusion with "self"

Forums > 100 Days of SwiftUI

I'm having a bit of trouble grasping the concept of self in swift. I did some additional searching and I've found out that using self prevents confusion (I'm not sure if I understood what I read correctly but it just got me more confused to be honest).

Here's a sample code that I also found

struct Person {
    var name: String

    func sayHello() {
        print("Hello, my name is \(self.name).")
    }
}

Why is self used here? Can't it be just

print("Hello, my name is \(name).")

I'm pretty sure it yields the same results which is why I can't seem to grasp the concept of using "self".

2      

Try this code:

import SwiftUI

struct Person {
    var name = "Taylor"

    func sayHello() {
        var name = "Taylor Swift"
        print("Hello, my name is \(self.name).")
        print("Hello, my name is \(name).")

    }
}

Person().sayHello()// I print both name variable contents. Taylor and Taylor Swift. 
print(Person().self) // I just print Person().self to give a general idea of what self actually is pointing to.

You'll notice there are two variables declared with the word name within the Person struct. One just under the struct and one of them as part of the sayHello function. In this example using self is how to let Xcode know which one you are talking about.
If you declare another variable or constant name under person struct e.g let secondName = "Ricky Bobby", you'll notice that the print(Person().self) will add that to the list of what is within the Person scope. And by then you should get the general idea what is meant by self.... You could just use different variable names everywhere within your struct or class to avoid the problem, but that has more cons than pros.

2      

Maybe this will also help - self

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.