Let’s say we need to find out what “respect” means in the dictionary. We would iterate through the pages of the dictionary until we found the word “respect” and read the definition. Although we had planned on going through the dictionary, we could break out of the loop after finding “respect”.
This same idea can be applied for loops as well. We can use the break
keyword to exit out of the loop before the loop fully completes:
let respect = 556 for pageNum in 1...1000 { if pageNum == respect { print("Respect means: to admire someone for their abilities.") break } print("On page \(pageNum) and still no 'respect'!") }
Prints out:
On page 1 and still no 'respect'! On page 2 and still no 'respect'! ... On page 555 and still no 'respect'! Respect means: to admire someone for their abilities.
In our loop, we plan to iterate from 1
to 1000
but after finding the correct pageNum
that defines “respect”, we break
out of our loop. Notice, the break
keyword will terminate the loop — we didn’t continue to print out "On page \(pageNum) and still no 'respect'!"
.
Instructions
In Break.swift, we have the structure of our for
-in
loop with a print()
statement at the end of it.
To complete the program, in the for-in
loop:
- Add an
if
statement that checks ifcounter
is equal toguessedNum
. - Inside the
if
body, print out the"It's [guessedNum]!!"
and replace[guessedNum]
with the actual value ofguessedNum
. - After the
print()
statement, add abreak
keyword.
After you pass this step, run the program a few times to get a sense of when break
is exiting the loop.