InterviewSolution
| 1. |
In case of capture list, do weak and unowned are substitutable to each other? |
|
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?() |
|