Did Swift drop the underscore-prefix convention for instance variables, e.g., _window? If so, why?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With