Learn
Loops
Using Underscore

Remember our “Smelly code” chalkboard? Smelly code, or often referred to as having a code smell refers to bad programming practices that make it hard for developers to work on their code. So it would be an appropriate punishment to make someone write, “I will not write smelly code” over and over again on a chalkboard.

Our goal, however, is to make this task easier using the power of loops, like so:

for num in 1...10 { print("I will not write smelly code.") }

But notice, we don’t actually use num in our loop body. Swift’s compiler actually gives us a warning which contains a message informing the developer of a potential issue or a suggested improvement:

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

We’ve seen these errors before when we wrote our loop but didn’t add any code inside its body. Therefore, to avoid the warning (i.e. code smell), it’s good practice to replace num with an underscore _:

for _ in 1...10 { print("I will not write smelly code.") }

In the example above, we don’t have to worry about the placeholder; we’re still able to print out "I will not write smelly code." ten times, and we don’t get a warning!

Instructions

1.

In Underscore.swift:

  • Write a for-in loop that uses an underscore _.
  • It should loop through the range 1...15.
  • During each iteration, print out a string to remind you of something. E.g.: "Buy eggs from the market".
Folder Icon

Take this course for free

Already have an account?