upbeat.it

by Cesare Rocchi

A selfless Swift

by Cesare Rocchi

It’s not a bird without ego :)

There’s quite a heated debate about the use of self. If you read the proposal on GitHub there are pros and cons. We had a similar discussion on the Ray Wenderlich team when we wrote our Swift style guide. I am in favor of using self, but I lost the argument :( And my argument is simple: I like code easy to read. I don’t mind writing self, even when it’s redundant, and I am sure my future self will appreciate it (no pun intended).

My knowledge of compilers is a bit rusty so I don’t even know if what I am proposing is doable. Also, my context is probably relevant:

  • I don’t exclusively use Swift. I use other languages like Ruby, Javascript and Go, which have a different semantics.
  • I don’t write code all day long. I might stay even 2-3 days without touching code.
  • I have been writing Objc for almost 10 years.
  • I like simple things, easy to remember :)

In an ideal world this would be the rule I’d use.

Always use self to access instance members.

I’d agree also on the following.

Never use self to access instance members.

I slightly prefer the first, but either way are easy because there are no exceptions.

I’d be fine with a situation like in Objc, where the exceptions about not using self are few and easy to remember:

  • init
  • dealloc
  • custom getter
  • custom setter

Here’s a little refresher written by Brent Simmons.




So far I have been adopting the following tactic:

  • don’t use self
  • if the compiler complains, add it

Sometimes I break the protocol though, because if I type self. I get relevant autocompletion options. So I write it just to give SourceKit some hint, then I delete it. Not ideal at all. It should be quite the opposite, I should be the one needing hints :)

Blocks complicate the situation, because the usage of self can lead to retain cycles, which you can solve with either weak or unowned. Two more options to remember :(

I hope Swift 3.0 will include an easy to conceptualize implementation of this matter, not just to favor me and my memory but to smoothen the learning curve for newcomers.