Is it necessary to always use [unowned self] in closures in Swift?
Hi everyone! I'm a beginner iOS developer and I'm having trouble understanding retain cycles in closures.
Here's a simple example: I'm making a network request inside a controller.
```swift
class ProfileViewController: UIViewController {
var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
fetchUserProfile()
}
func fetchUserProfile() {
APIClient.shared.getUserProfile { [weak self] profile in
self?.nameLabel.text = profile.name
}
}
}
```
I see that many people use `[weak self]`, but some write `[unowned self]`. What's the difference? When should I use `unowned`? Or is it better to always use `weak`?
I've heard that `unowned` can cause a crash if the object is
No answers yet.
Log in to leave an answer