Skip to content

Instantly share code, notes, and snippets.

@cdzombak
Created December 17, 2014 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdzombak/94caa543649454e842cd to your computer and use it in GitHub Desktop.
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.
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
}
@robrix
Copy link

robrix commented Dec 18, 2014

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.

@robrix
Copy link

robrix commented Dec 18, 2014

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