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

Question: the sequence of events happening in this code

Forums > 100 Days of SwiftUI



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



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.




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 ?


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!

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.