In Swift, the underscore “_” is used in a “for-in” loop to represent a value or a variable that is not needed or used.
When working with loops, there may be cases where you only need to execute an action a certain number of times, and the value from the loop’s counter isn’t relevant.
In such cases, replacing the value with an underscore indicates to the program that you don’t need to store any values, means you don’t need to set a variable for this loop.
for _ in 1...3 { print("Why using underscore in a for-in loop in Swift?") } /* Output Why using underscore in a for-in loop in Swift? Why using underscore in a for-in loop in Swift? Why using underscore in a for-in loop in Swift? */
Quick notes
- In this code, we only need to execute the “print” statement three times, and we don’t need to use the value of a counter variable.
- Using an underscore in place of the variable name makes it clear that we don’t need the variable.
- In summary, when you use the underscore in a “for-in” loop in Swift, it tells the program that you don’t need or use the value of the counter variable.
Using underscore instead of a variable which needs to be defined at the beginning, can make the code more concise and easier to read when the variable isn’t needed.