0

Going through the Apple documentation for Swift, I'm designed a for loop that creates 5 buttons to act as "stars" in a 5-star rating feature.

I noticed that the for loop is constructed as follows:

for _ in 0...<5 

And in the explanation for this, Apple mentions that you can use a wildcard _ operator when you don't need to know which iteration of the loop is currently executing.

But what's the upside to not knowing the iteration? Is it a memory saving issue optimization? Is there ever a scenario where you don't want to know the iteration?

4 Answers4

4

In general, unused variables add semantic overhead to code. When someone reads your code, they need to make an effort to understand the function of each line and identifier, so that they can accurately anticipate the impact of changing the code. A wildcard operator allows you to communicate that a value that is required by the syntax of the language is not relevant to the code that follows (and is not, in fact, even referenced).

In your specific example, a loop might well need executing a certain number of times, but if you want to do the exact same thing on each iteration, the iteration count is irrelevant. It's not especially common, but it does happen. The semantic overhead in this case is low, but it's meaningful (you're making it clear from the start that you intend to do the same thing every time), and it's a good habit to get in, broadly.

Seamus Campbell
  • 17,816
  • 3
  • 52
  • 60
3

The for loop index needs to be stored in memory, so this won't serve as any kind of memory optimization.

I think most importantly it easily conveys to readers of the code that the loop index is not important.

Additionally, it prevents you from having to come up with some arbitrary dummy variable name. It also declutters your name space when you're debugging inside the loop, since you won't be shown this dummy variable.

Alexander
  • 59,041
  • 12
  • 98
  • 151
3

Is there ever a scenario where you don't want to know the iteration?

Certainly. Consider:

func echo(_ s:String, times:Int) -> String {
    var result = ""
    for _ in 1...times { result += s }
    return result
}

How would you write it?

matt
  • 515,959
  • 87
  • 875
  • 1,141
1

This is not necessarily about knowing the iteration. When you don't need to know the element inside the loop you are iterating. The underscore is that placeholder - just as the underscore is the symbol in the declaration suppressing externalization of the name. Check this SO Thread for more detail about this.

Community
  • 1
  • 1
Jeet
  • 5,569
  • 8
  • 43
  • 75