Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an underscore "_" before a swift variable mean?

Tags:

ios

swift

Here is the code:

var _selected: Bool = false {
    didSet(selected) {
        let animation = CATransition()
        animation.type = kCATransitionFade
        animation.duration = 0.15
        self.label.layer.addAnimation(animation, forKey: "")
        self.label.font = self.selected ? self.highlightedFont : self.font
    }
}

Why the variable is "_selected" instead of "selected"?

like image 463
user2892270 Avatar asked Jun 03 '15 02:06

user2892270


People also ask

What does an 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.

What does an underscore before a variable mean?

An underscore in front usually indicates an instance variable as opposed to a local variable. It's merely a coding style that can be omitted in favor of "speaking" variable names and small classes that don't do too many things. Follow this answer to receive notifications.

What is argument label in Swift?

The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.


Video Answer


1 Answers

It's simply a coding style that shouldn't apply to Swift code.

Developers often mark things with an underscore to indicate that it should be private.

That said, there IS a practical use for the underscore _. Read more about Local and External Parameter Names for Methods.


So how do you avoid using _selected? Right now you have two variables when you already have the one you need (selected).

Removing the _ will require you to override the member variable (how this should be done).

override var selected: Bool {
    didSet {
        println("Hello, \(selected)")
    }
}

Additionally, a table view cell will have an overridable method setSelected(selected:animated) that might be worth exploring.

like image 60
David McGraw Avatar answered Oct 23 '22 03:10

David McGraw