Advanced Swift: Memory Management · Challenge: Fix the Leak 2 | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1940727-advanced-swift-memory-management/lessons/8

hey, wouldn’t it be better just to capture [who] instead of [weak self]?
lazy var greetingMaker: ()->String = { [who] in
return “Hello (who)”
}

Great point! Yes, you totally could and some prefer the minimal capture style.

Even though this toy example doesn’t capture it (haha, pun), [who] and [weak self] have a different semantic meaning. In the first you are just making a copy of the string, in the second you are asking if the object is still exists. You might not want the closure to run if the whole object is not around. Especially true if the closure performs some sort of more interesting mutation on the object.

You make a really great point though, and something I should probably talk about in a future rev of this course. Thanks for posting.

Thanks for the reply and explanation! Honestly I almost never used the first [who] approach in Swift in the past. Not sure why, because I knew about it already. Now after watching this course I find it really appealing as it helps to show your intentions more explicitly. Probably didn’t think about the reasoning behind it enough :slight_smile:
Anyway if you could add extra episode about memory management in IOS with ViewControllers, animations, segues etc it would be great (for example when we don’t need to worry about capturing self etc. and not pollute the code with unnecessary weak self)