Protection from Retain Cycles, Require Self all the time
Opened this issue · 2 comments
Thanks for this awesome guide, very detailed and informative and helped me so much.
I have 1 issue with the Protection From Retain Cycles section. You said
"We found that we made less mistakes when we just required self all the time than if we have to decide wether to write it or not"
I dont understand how this makes sense, the opposite actually should be the case.
If you only use self when required (e.g in closures) it is much easier to spot a potential retain cycle because when the compiler requires you to write self, you know you will most likely deal with a retain cycle.
If you use self all the time than I cannot see how that will make your life easier.
Also code should be more readable.
Hi, thanks for the feedback!
We understand that the current guidelines sound counterintuitive considering Swift's compile-time checks. The key here is that this guideline does not work by itself alone, but works together with the other guideline that states:
For all non-@noescape and non-animation closures, accessing self within the closure requires a [weak self] declaration.
We decided on these guidelines for two reasons:
- While the Swift compiler forces explicit capturing by requiring
self
, in the end it is the programmer's responsibility to decide wether to capture thatself
strongly or weakly. Relying on the compiler to decide whether to writeself
or not tends to result in strong captures just because writingself
already removes the compiler error. - About 30-40% of our "legacy" code is still written in Objective-C. The danger here is that programmers tend to bring coding practices from one language to the other, including the weak-ing of
self
. Once programmers get used to relying on Swift's stricter compiler, memory leaks get "leaked" into Objective-C code.
We do know that these are both reasons that should be negated with good code reviews and skilled developers. But as we have mentioned in the Intro, we wanted guidelines that would fit in a team environment, where everyone's background, skills, expertise, style differ.
We do challenge some of our guidelines on a regular basis, finding new approaches and adopting to the Swift changes. We actually plan to rethink some of the core guidelines once Swift 3 gets finalized and most of our Objective-C core codebase gets ported to Swift.
I think this should still be updated. We should not use self
in Swift unless explicitly required. Apple even rejected a proposal that would force us to use self
at all times. It is not Swifty to use self
unless we have to. Code is harder to read and retain cycles may be harder to spot.
Please update this otherwise awesome guide