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

Question: the sequence of events happening in this code

Forums > 100 Days of SwiftUI

@boat  

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

2      

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.

3      

@boat  

@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 ?

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.