Swift: The break Keyword

break Keyword in Swift:

Assume we want to look up the definition of “trust” in the dictionary. We’d go through the dictionary’s pages until we came across the word “trust” and read the definition. We could break out of the loop after finding “trust”, even though we had planned to go through the dictionary. So, we use break keyword for this purpose in Swift.

Loops can be used in the same way. We can break out of the loop before it fully completes by using the break keyword:

let trust = 433;
 
for pgNo in 1...1000 {
  if pgNo == trust {
    print("Trust means: firm belief in truth.");
    break;
  }
  print("Still no 'trust' on page \(pgNo)!");
}

It prints out as follows:

Still no 'trust' on page 1!
Still no 'trust' on page 2!
.
'
'
Still no 'trust' on page 432!
Trust means: firm belief in truth.

We planned to iterate from 1 to 1000 in our loop, but we break out after finding the correct pgNo that defines “respect”. The word trust is on page 433 so the code will print "Still no 'trust' on page \(pgNo)!" for 432 times ( shorten the output in the window above). We didn’t continue to print it because we used the break keyword to end the loop.

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: