[swift-evolution] Add something like [unowned self] syntax for passing instance methods into closure parameters without creating retain cycles

Karl Wagner razielim at gmail.com
Tue Sep 13 22:29:08 CDT 2016


> Honestly, I’d be fine with / prefer only allowing unowned (at all) if it’s @noescape, if that, requiring strong or weak for anything that escapes. That seems to go along with swift’s emphasis on safety. 
What?!?!! That's an extraordinary thing to say.
I don't think you understand what autozeroing weak references are for. They are not there so that you can have gaps in your reasoning of your code, or to allow undefined behaviour. They exist so that you can have a non-retaining pointer (I.e. Unowned), where the pointee's lifetime is independent of the reference. So when the pointee does deallocate at some unknown time, the pointer reverts to nil doesn't just dangle in to invalid memory.
Let's say I have some reusable functionality, like an input handler for text-processing events with a particular behaviour (maybe it does some validation or something, it's not important). I can encapsulate that as a class (maybe it can't be a struct, that's my business. Maybe it has specialised subclasses or requires identity). Now I have my UIViewController, I create and retain an instance of that class, but the object needs to dispatch events back to the UIVC so it needs a non-strong pointer to its parent.
The parent and child have coupled lifetimes. There will never be an orphaned child; and if there is, and it's handling events and dispatching them nowhere, that's a serious flaw in the application logic. Of course users don't want applications to crash, but developers do! When there are failures in the application logic, I want them to be loud and obvious. Otherwise, we might as well remove all preconditions as other runtime assertions as well.
Some of the comments here about unowned references are scary; you should always understand your application logic, and use of unowned pointers is completely safe if you do. If you're using weak references as a shorthand for a lack of understanding of your own code, you have a bigger problem than an esoteric crashing bug.
It's similar to Linus' argument against using kernel debuggers (https://lwn.net/2000/0914/a/lt-debugger.php3). Understanding your code at a level above the source, and being careful, make you a better developer. There are no features in swift which compensate for a lack of understanding about how your code works.
	
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160914/7f6a31b8/attachment.html>


More information about the swift-evolution mailing list