<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body dir="auto"><div><span style="background-color: rgba(255, 255, 255, 0);">Teach init a 'defer'-like ability to deinit<br><br>'defer' is a great way to ensure some clean up code is run; it's declaritive locality to the resource acquisition is a boon to clarity.<br><br>Swift offers no support for resources acquired during 'init'.<br><br>For an example, from <a dir="ltr" href="https://www.mikeash.com/pyblog/friday-qa-2015-04-17-lets-build-swiftarray.html" x-apple-data-detectors="true" x-apple-data-detectors-type="link" x-apple-data-detectors-result="0">https://www.mikeash.com/pyblog/friday-qa-2015-04-17-lets-build-swiftarray.html</a><br><br>init(count: Int = 0, ptr: UnsafeMutablePointer<T> = nil) {<br> self.count = count<br> self.space = count<br><br> self.ptr = UnsafeMutablePointer<T>.alloc(count)<br> self.ptr.initializeFrom(ptr, count: count)<br>}<br><br>deinit {<br> ptr.destroy(...)<br> ptr.dealloc(...)<br>}<br><br>Another 'resource' might be adding an NSNotificationCenter observer, and wanting to unobserve in deinit (no need in OS X 10.11, iOS 9, but for earlier releases this is a valid example).<br><br>Changing the above code to use a 'defer' style deinit block might look like:<br><br>init(count: Int = 0, ptr: UnsafeMutablePointer<T> = nil) {<br> self.count = count<br> self.space = count<br><br> self.ptr = UnsafeMutablePointer<T>.alloc(count)<br> self.ptr.initializeFrom(ptr, count: count)<br><br> deinit {<br> ptr.destroy(...)<br> ptr.dealloc(...)<br> }<br><br> // NSNotificationCenter example too<br> NSNotificationCenter.defaultCenter().addObserver(...)<br> deinit { <br> NSNotificationCenter.defaultCenter().removeObserver(...)<br> }<br>}<br><br>The need to provide a separate implemention of deinit is gone. Reasoning for 'defer' applies here. There is good locality between what was initialized and what needs cleaning up.<br><br>Considerations:<br>1. Should deinit blocks be invoked before or after code in an explicit deinit method?<br>2. Should deinit blocks be allowed in other methods; e.g. viewDidLoad()?<br>3. How should deinit blocks be prevented from strongly capturing self (thus preventing themselves from ever running!)?<br><br></span><br>Cheers,<div>Graham Perks.</div></div></body></html>