Break
Part of the Fundamentals section of Coddy's Swift journey — lesson 45 of 86.
Sometimes you need to exit a loop early, before it finishes all its iterations. The break statement immediately stops the loop and continues with the code after it.
for number in 1...10 {
if number == 5 {
break
}
print(number)
}
// Output: 1, 2, 3, 4When number reaches 5, the break statement executes and the loop stops completely. Notice that 5 itself is never printed because break exits before reaching the print statement.
The break statement works with all loop types. Here's an example with a while loop that searches for a specific value:
var count = 0
while true {
count += 1
if count == 3 {
break
}
}
print(count) // Output: 3This pattern is useful when you're searching for something and want to stop as soon as you find it, rather than continuing through unnecessary iterations.
Challenge
EasyWrite a function findFirstMultiple that takes limit and divisor and returns the first number (starting from 1) that is divisible by the divisor.
Use a loop to iterate through numbers starting from 1 up to the limit. When you find a number divisible by the divisor, use break to exit the loop immediately and return that number.
Logic:
- Loop through numbers from 1 to
limit - Check if the current number is divisible by
divisor(remainder is 0) - If found, break out of the loop and return that number
- If no multiple is found within the limit, return
-1
Parameters:
limit(Int): The upper bound for the search (inclusive)divisor(Int): The number to check divisibility against
Returns: The first number divisible by the divisor, or -1 if none found (Int)
For example, if limit is 10 and divisor is 3, the function returns 3 (the first number divisible by 3).
Cheat sheet
The break statement immediately stops a loop and continues with the code after it:
for number in 1...10 {
if number == 5 {
break
}
print(number)
}
// Output: 1, 2, 3, 4When break executes, the loop stops completely. The value that triggers the break is not processed by subsequent statements in the loop.
The break statement works with all loop types, including while loops:
var count = 0
while true {
count += 1
if count == 3 {
break
}
}
print(count) // Output: 3This pattern is useful for searching and stopping as soon as a condition is met, avoiding unnecessary iterations.
Try it yourself
func findFirstMultiple(limit: Int, divisor: Int) -> Int {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input