BLACK FRIDAY SALE: 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 \(")

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


Try this code:

import SwiftUI

struct Person {
    var name = "Taylor"

    func sayHello() {
        var name = "Taylor Swift"
        print("Hello, my name is \(")
        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.


Maybe this will also help - self


Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

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.