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

Question: the sequence of events happening in this code

Forums > 100 Days of SwiftUI

Hello,

When Paul introduced init and deinit for class, he demonstrated the code below.
I understand the syntax, but I failed to understand the order of the code turning out.

Code here

class User {
    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 = User(id: i)
    print("User \(user.id): I'm in control!")
}

Below is how the code turns out

User 1 : I am alive! User 1: I am in control! USer 1 : I am dead! User 2 : I am alive! User 2: I am in control! USer 2 : I am dead! User 3 : I am alive! User 3: I am in control! USer 3 : I am dead!

Question: shouldn't it be in the order of:

I'm alive. I'm dead. I'm in control

how come the I'm in control showing between alive and dead ?

Thank you in advance

Boat

   

deinit is run when the instance is destroyed, which doesn't occur until the end of each iteration through the loop.

So the sequence of events is:

for i in 1...3 {
    let user = User(id: i)  // 1. instance created
    print("User \(user.id): I'm in control!")  // 2. instance used
    // 3. instance destroyed
}

I'm alive. I'm dead. I'm in control

If it occurred in this order, the code would crash because when you tried to print "I'm in control", there would no longer be an instance of User to supply user.id.

1      

@roosterboy,

the reason that I'm alive gets printed out FIRST, is becuaseu it was included in the initializer, meaning it has to be printed when i is assigned to id (i.e an instance is created) , as part of the initialization process (which is NOT optional or could be skipped)

Right ?

   

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out 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.