Have you heard of strong and weak references? They're two different types of references in Swift that can impact how your objects are deallocated when they're no longer in use.
In this article, we'll go over two code examples to show you exactly how they work. One example will use strong references, while the other will use weak references.
Let's create a Account class to use later in the examples:
class Account {
let name: String
init(name: String) {
self.name = name
}
deinit {
print("\(name) account has been deallocated")
}
} Strong References
class Manager {
let name: String
var account: Account?
init(name: String, account: Account?) {
self.name = name
self.account = account
}
deinit {
print("\(name) has been deallocated")
}
}
var manager: Manager? = Manager(name: "John", account: nil)
var accountManager: Account? = Account(name: "John")
manager?.account = accountManager
accountManager = nil
if let name = manager?.account?.name {
print(name)
}
Here's the important part: even if we set accountManager to
nil, the Account instance still exists in memory
because Manager is still holding a strong reference to it. This
means the Account instance won't be deallocated until all of its
strong references are removed.
Weak References
class Employee {
var name: String
weak var account: Account?
init(name: String, account: Account?) {
self.name = name
self.account = account
}
deinit {
print("\(name) has been deallocated")
}
}
var employee: Employee? = Employee(name: "Patrick", account: nil)
var employeeAccount: Account? = Account(name: "Patrick")
employee?.account = employeeAccount
employeeAccount = nil
if let name = employee?.account?.name {
print(name)
}
In the code example using a weak reference to account, when we
set employeeAccount to nil, the reference to
account from the Employee instance becomes
nil and the account is deallocated.
By using strong and weak references correctly, you can ensure that your Swift code is both efficient and safe, and avoid common pitfalls that can lead to memory leaks and other issues. I hope this article has helped you gain a better understanding of strong and weak references in Swift, and that you feel more confident using them in your own projects.
Happy coding.
Check my GitHub repos about design patterns with Swift: github.com/HaraldBregu