Main features of Deinitializers
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!
*/
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!
*/
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!
*/