InterviewSolution
| 1. |
class LogInViewController: UIViewController { var NetworkManager = NetworkManager() } func loginAction(){ let loginVC = myStoryboard.instantiateViewController(withIdentifier: "LogInViewController") as! LogInViewController loginVC.networkManager.doSomeAction() } |
|
Answer» NO - They are similar but have a slightly different purpose. Swift DOCUMENT SAYS, “If you assign a closure to a property of a class instance, and the closure captures that instance by referring to the instance or its MEMBERS, you will create a strong reference cycle between the closure and the instance.” See below example. class Device { var closure: (() -> ())? var name = "iPad" init() { self.closure = { print("inventory has \(self.name)") } } }var iPad:Device? = Device() iPad?.closure?() iPad = nilHere device instance iPad will never be released DUE to a strong reference cycle as described. So we have to use a capture list. Capture lists help us avoid memory problems. Inside the capture list, we can use weak or unowned to avoid any strong reference. weak: use weak when the captured VALUE may become nil. class Device { var closure: (() -> ())? var name = "iPad" init() { self.closure = {[weak self] in print("inventory has \(self?.name)") } } }var iPad:Device? iPad = Device() iPad?.closure?() iPad = nilunowned: If we know for sure captured value will never become nil while the closure is called. In the below code, We are creating a non-nil instance of the device. So will sure that name will be always available. class Device { var closure: (() -> ())? var name = "iPad" init() { self.closure = {[unowned self] in print("inventory has \(self.name)") } } }var iPad = Device() iPad.closure?() |
|