Swift: Using Underscore

Using Underscore in Swift:

Bad programming practices that make it difficult for developers to work on their code are referred to as smelly code. As a result, making someone write “I will not write smelly code” over and over on a chalkboard would be an appropriate punishment. So, using underscore in Swift is very useful for this purpose.

Our goal, on the other hand, is to use the power of loops to make this task easier, as shown below:

for count in 1...10 {
  print("I'm not going to write smelly code.");
}

In the above code, notice that count is not declared in our loop body. Swift’s compiler issues a warning with a message informing the developer of a potential problem or a suggestion for improvement:

immutable value 'count' was never used; consider replacing with '_' or removing it

We’ve seen these errors before when we created a loop but didn’t include any code in the body. As a result, it’s best to replace count with an underscore _: to avoid the warning (i.e. code smell).

for _ in 1...10 {
  print("I'm not going to write smelly code.");
}

We don’t have to worry about the placeholder in the example above; we can print “I'm not going to write smelly code.” ten times without a warning!

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: