Created
December 17, 2014 18:55
-
-
Save cdzombak/94caa543649454e842cd to your computer and use it in GitHub Desktop.
Is omitting `self`, per [github/swift-style-guide](https://github.com/github/swift-style-guide#only-explicitly-refer-to-self-when-required) always the best? In this example, I argue: yes, the second version is more verbose, but that verbosity is a good thing; it adds clarity to the intention of this method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
override func loadView() { | |
let webView = UIWebView() | |
webView.delegate = self | |
webView.backgroundColor = UIColor.nl_offWhite() | |
view = webView | |
} | |
// vs. | |
override func loadView() { | |
let webView = UIWebView() | |
webView.delegate = self | |
webView.backgroundColor = UIColor.nl_offWhite() | |
self.view = webView | |
} |
Also like un-braced if
statements, I consider this to be a flaw of the language. Shadowing the scope’s variables vs. using self
would be purely stylistic if self
’s ownership had to be explicitly stated in any closure it appeared in.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As noted on Twitter, our style guide was designed explicitly to prevent this usage. It dilutes the meaning of
self.
in other, more subtle contexts, most notably closure capture.You can copy and paste the second version into a closure assigned to a property on
self
and now you have a reference cycle. The first version will cause a compiler error, which will require you to explicitly address the capture semantics rather than just leaving them at the default strong reference.I consider this a bug waiting to happen, almost on a par with un-braced
if
statements in C.