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

day 10

Forums > 100 Days of SwiftUI

I have a question regarding this code:

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)

Why cannot we just do following:

struct Player {
    let name: String
    let number = Int.random(in: 1...99)

}

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

   

Welcome to Hacking with SwiftUI!

You're asking a question from Day 10 from a lesson titled How to Create Custom Initializers

See -> Day 10 Lesson

struct Player {
    let name:   String
    let number: Int // 👈🏼 This is a place holder. It must be initialised somewhere.

    //   👇🏼 This is a custom initializer. It's the focus of the lesson.
    init(name: String) {
        self.name = name
        number = Int.random(in: 1...99) // 👈🏼 Here! Initialise it in a custom initialiser.
    }
}

let player = Player(name: "Megan R")
print(player.number)  // prints "42" (probably)

There are a few ways to initialise a struct's variables and you offered an example in your question above. That's a fine way to initialize a variable, but it doesn't illustrate the process of using a Custom Initializer.

Keep Coding!

1      

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.