5

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.

5

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.

  • Generally good advice, but let me add that it also depends on the background of your group. If they come from Java, typical (but not always) style is to leave out unnecessary thiss. However, if they come from Python or Javascript, they are used to putting in this or self. – user949300 Jan 10 '15 at 19:20
  • It also helps to give member variable names a prefix like "d_" or "m_", though I'm not sure how common that is outside of C++. – Ixrec Jan 10 '15 at 22:22
2

Not using self will make you think twice any time you use a variable. IMHO writing clean code is a matter of style. The style in Objective-C is to use self with properties. Since the vast majority of Swift programmers come from Obj-C, this style should be kept.

  • 2
    That is not a style in Objective-C, it is mandatory. In Swift you have a choice. "I have always done it that way in another language" is not a good reason to keep doing it that way. – fishinear Oct 31 '16 at 12:07
  • @fishinear: we are talking about the same framework here, not just another language. Again: I think as simpler code can be read, the better it is. Also in ObjC you could call the ivar with the _-prefix (which is not exacly the same as self, but othen used synonymously). – brainray Oct 31 '16 at 12:50
1

Specifically in the case of Swift, I believe there are a few benefits to leaving out self unless explicitly required by the compiler:

  1. Using self only where required (i.e. in closures where self is captured) makes it much easier to spot situations where references to self may be improperly retained.

  2. I ran into an interesting issue where the use of self appears to prevent warning messages from being shown:

class MyObject {
    var myRange: Range‹Int›? {
        willSet {
            // This line has a warning that you are operating on a property that is about to change
            myRange?.startIndex = 2
            // This line does not show any warning
            self.myRange?.endIndex = 3
        }
    }
}

You might argue that this is a bug, but I think it's important that self changes the way some expressions are treated, if only for warnings.

  • In swift 3, I get an error on both of these. – fishinear Oct 31 '16 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.