UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

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.