I have a ViewController class as shown below:
class ViewController {
var viewModel = ViewModel()
viewDidLoad() {
self.viewModel.showAlert = { [weak self] in
self?.alert()
}
}
func alert() {
// alert logic
}
}
Here is the ViewModel class
class ViewModel {
var showAlert: (() -> Void)?
}
Now, does this create a strong reference cycle or not?
And if this creates one, then what to use - weak or unowned?
This does not create a strong reference cycle, because you used
weak self.ViewControllerholds a strong reference toViewModel.ViewModelholds a strong reference to a closure. The closure holds a weak reference to theViewController:As long as
ViewControlleris deallocated (this happens when you dismiss it for example),ViewModelwill be as well.