Search code examples
swift

Swift Instance Variable Underscore Prefix?


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


Solution

  • 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.