Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this underscore mean in Swift?

Tags:

xcode

ios

swift

I used the map function in Swift to iterate on a bunch of subviews and remove them from a superview.

self.buttons.map { $0.removeFromSuperview() }

When I upgraded from Swift 1.x to 2.0, Xcode gave a warning that the return value from map was unused. So I assigned it with let x = ... and I got another warning:

enter image description here

So I let Xcode fix the warning for me, and it gave me this:

_ = self.buttons.map { $0.removeFromSuperview() }

What is the significance of an underscore when not in the context of a method parameter? What does it mean?

Edit:

I do know that when a method parameter is anonymous, the underscore takes their place. I'm talking about an underscore in the middle of a method. It's not part of a message.

like image 523
Moshe Avatar asked Nov 10 '15 01:11

Moshe


People also ask

What is _ variable in Swift?

1. Swift Variables. In programming, a variable is a container (storage area) to hold data. For example, var num = 10. Here, num is a variable storing the value 10.

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.


2 Answers

An underscore denotes the fact that you need to set a variable, but you do not plan on using the variable in the future. Instead of giving it an elaborate name, an underscore will be more simple and less clutter, especially in the case that the variable name doesn't matter. (since you do not use it again.)

like image 145
Acoop Avatar answered Oct 18 '22 08:10

Acoop


A parameter whose local name is an underscore is ignored. The caller must supply an argument, but it has no name within the function body and cannot be referred to there. It is basically a parameter placeholder that you are not going to use for anything in the body.

like image 35
Caleb Bach Avatar answered Oct 18 '22 09:10

Caleb Bach