WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.