Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Instance Variable Underscore Prefix?

Tags:

swift

Did Swift drop the underscore-prefix convention for instance variables, e.g., _window? If so, why?

like image 832
ma11hew28 Avatar asked Jun 13 '14 22:06

ma11hew28


People also ask

What is the use of _ in Swift?

In Swift, the underscore operator (_) represents an unnamed parameter/label. In for loops, using the underscore looping parameter is practical if you do not need the looping parameter in the loop. In function calls, you can omit the argument label by adding a (_) in front of the argument in the implementation.

What does the underscore mean in Swift?

There are a few nuances to different use cases, but generally an underscore means "ignore this". When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing.

Can you start variable with underscore?

Well Underscore character(_) begin with your variable name is discouraged but it is legal and some people use it to identify as an private variable and some for naming it in caching variable.


3 Answers

Apple still uses _ in its Xcode boilerplate code as a convention for a non-public variable. You'll see a pattern like such:

class Foo {
  var _bar : Bar? = nil
  var  bar : Bar {
    if _bar == nil {
      /* compute some stuff */
      _bar = Bar (/* ... */)
    }
    return _bar!
  }
}

where access to the property is meant to be through the bar computed property. You find this in Apple CoreData templates.

like image 184
GoZoner Avatar answered Oct 09 '22 17:10

GoZoner


In Objective-C when you declare a property @synthesize would create the getter and setters for you automatically since clang 3.2. So, the default @synthesize for a property "foo" would look like this:

@synthesize foo = _foo

because of that _foo would then be the iVar. In other words you could have done the @synthesize yourself and called the iVar whatever you liked:

@synthesize foo = myiVarFoo

so in this case there is no "_"

So now in Swift from the documentation:

Swift unifies these concepts into a single property declaration. A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly.

So from the documentation it's clear that swift does not have a corresponding instance variable thus no need to have the "_" around anymore.

like image 41
zumzum Avatar answered Oct 09 '22 16:10

zumzum


The underscore prefix was meant not to confuse the instance variable _foo with its getter foo.

In swift there's not such distinction between ivars and getters. Instead you only have properties, making the _ convention non necessary.

like image 30
Gabriele Petronella Avatar answered Oct 09 '22 16:10

Gabriele Petronella