Deinitializer

#deinit #deinitializer

Overview

Main features of Deinitializers

  • Cannot be used with func.

  • They never take parameters or return data.

  • They run when the last copy of a class instance is destroyed.

  • Cannot be called directly.

  • Since Structs are unique and cannot be copied, they don't have deinitializers.

Sample Codes

Example 1

Without deinit
class User {
    let id: Int

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

}

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

/*
print:

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

*/
With deinit
class User {
    let id: Int

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

}

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

/*
print:

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

*/

Example 2

class User {
    let id: Int

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

    deinit {
        print("User \(id): I'm dead!")
    }
    
}

var users = [User]()

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

print("Loop is finished!")
users.removeAll()
print("Array is clear!")

/*
print:

User 1: I'm alive!
User 1: I'm in control!
User 2: I'm alive!
User 2: I'm in control!
User 3: I'm alive!
User 3: I'm in control!
Loop is finished!
User 1: I'm dead!
User 2: I'm dead!
User 3: I'm dead!
Array is clear!

*/

Sources

Videos

Articles / Documents

Last updated