UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 15 - Class Deinitializer Random Output

Forums > 100 Days of SwiftUI

Hey All,

I'm working through typing hand-by-hand the Day 15 Swift in 1 hour consolidation and I noticed an abnormality in the console when running through class deinitializers.

class NewUser {
    let id: Int

    init(id: Int) {
        self.id = id
        print("User \(id): I'm alive!")
    }
    deinit {
        print("User \(id): I'm dead!")
    }
}

for i in 1 ... 3 {
    let user = NewUser(id: i)
    print("User \(id): I'm in control!")
}

for some reason, when this runs the consol spits out a a random user ID for each loop. the id changes each time. anyone have any idea why that's getting returned?

User 1: I'm alive!
User 247: I'm in control!
User 1: I'm dead!
User 2: I'm alive!
User 247: I'm in control!
User 2: I'm dead!
User 3: I'm alive!
User 247: I'm in control!
User 3: I'm dead!

2      

print("User \(id): I'm in control!")

id doesn't belong to any instance of NewUser, so it doesn't correspond to the id property of user.

You need to do this instead to get the result you are expecting:

print("User \(user.id): I'm in control!")

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.