TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.