GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Day 10: Custom Initializers

Forums > 100 Days of SwiftUI

In the custom initializer lesson, why do we use self.name, but not self.number?

It seems to compile either way.

struct Player {
    let name: String
    let number: Int

    init(name: String) {
        self.name = name
        number = Int.random(in: 1...99)
    }
}

let player = Player(name: "Megan R")
print(player.number)

   

Because you have a property in Player called name and you also have a parameter to the initializer called name. So in your init, which one does name refer to?

We use self.name to indicate specifically that we are setting the name property of the Player struct to the value held in the name parameter to the initializer.

1      

so, if they werent both "name" you wouldnt use self?

   

Correct. Like if, for instance, your init was this instead:

    init(handle: String) {
        name = handle
        number = Int.random(in: 1...99)
    }

Here, name clearly refers to the property of Player; it can't be anything else, so there's no possibility of confusion and thus no need for self. to clarify.

I should mention that while you don't have to use self. in the above example, you could. I've seen some people who prefer to always use it in initializers just to make it crystal clear that they are setting the value of properties, even if such use isn't strictly necessary all the time.

2      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.