Swift Coding Style – Using Optional ‘self’ Reference in Instance Methods

coding-styleswift-language

Swift allows optional prefixing of method calls and property references to the current object instance via self. Removing these prefixes can declutter code but, depending on the length of the method and number of parameters and local variables, it can also make variable scope ambiguous.

Perhaps the answer is to refactor into smaller classes and methods, but sometimes that isn't always practical. Common examples are things like UIViewController subclasses and custom viewDidLoad() implementations or complex action handlers for UIGestureRecognizer subclasses. I've thought about this a bit since diving into developing an iOS app in Swift but am still on the fence. My ideal answer(s) would touch on:

  1. If not referencing self has an practical downsides.

  2. Whether mixing implicit and explicit references to self is worse that sticking to one or the other (I'm leaning towards yes).

  3. Overall stylistic concerns with a focus on readability.

  4. Instance variable naming styles versus local variable naming styles to mitigate ambiguity.

  5. References to similar issues in other languages.

Best Answer

I believe this is nothing but a matter of style - no "measure of readability" (which is always personal) can help you here.

So before I go any further, let me say this: Whatever the style choice, if you're working in a team, define a clear standard that the whole team must comply with, because if there is one thing that everyone can agree on that makes code less readable, is having to keep up with different style choices as you read it.

But now to the main subject: self, this or me, as present in many OO languages, are featured roughly for the following reasons:

  1. Being able to pass an instance of the current object to others;
  2. Accessing special properties that are otherwise unavailable, such as reflective property this.class in Java;
  3. To allow otherwise conflicting names to be used in local scopes.

As with many other details that are abstracted away from us when we use OO languages (vtables, etc...), self could also be hidden, if it weren't for the reasons above.

So my opinion is that you should only use it when necessary, as above. Of course, this idea only works well along with the practice of making small classes and methods; otherwise, both your local and global scopes are going to be so big that it will always be confusing, forcing the reader to jump up and down in the code, looking for the definitions. But I'm tempted to say, in these cases, that it is not the consistency of style that is going to save you.

Related Topic