Capture List Optimization

Is there such a thing? Is there a difference between the two below? Is one more โ€œrightโ€ than the other?

All objects are properties self(say, a view controller) and have the same lifetime as self. We can introduce an object with a shorter lifetime than selfthat which will be weak, but the same question applies.

objectOne.doSomething { [unowned self] in
    self.objectTwo.finish()
    self.tableView.reloadData()
    // self.someDelegate?.didFinishSomething()
}

against

objectOne.doSomething { 
    [unowned objectTwo = self.objectTwo,
    unowned tableView = self.tableView
    // weak someDelegate = self.delegate
    ] in
    objectTwo.finish()
    tableView.reloadData()
    // someDelegate?.didFinishSomething()
}

Apple has this example in their docs :

lazy var someClosure: () -> String = {
    [unowned self, weak delegate = self.delegate!] in
    // closure body goes here

    delegate?.doSomething()
}

In this case, it delegatemay have a shorter service life than self, but why not use it like that?

lazy var someClosure: () -> String = { 
    [unowned self] in
    // closure body goes here

    self.delegate?.doSomething()
}
+4
source share
2 answers

Yes, there is an important difference. In the case of Apple docs, the alternative code you presented:

lazy var someClosure: () -> String = { 
    [unowned self] in
    // closure body goes here

    self.delegate?.doSomething()
}

delegate self .

Apple:

lazy var someClosure: () -> String = {
    [unowned self, weak delegate = self.delegate!] in
    // closure body goes here

    delegate?.doSomething()
}

delegate var delegate self, , . , self.delegate , , Apple nil (, ) .

, , ([someIdentifier = someProperty]) , , . , ([weak self]) "", ({ self?.someProperty }), , , .

+1

, [unowned objectOne = self.objectOne], lazy var UIViews : , lazy init , . , superview.addSubview(objectOne) init lazy, superview, objectOne .

0

Source: https://habr.com/ru/post/1691299/


All Articles