Breaking a loop

suggest change

A loop will execute as long as its condition remains true, but you can stop it manually using the break keyword. For example:

var peopleArray = ["John", "Nicole", "Thomas", "Richard", "Brian", "Novak", "Vick", "Amanda", "Sonya"]
var positionOfNovak = 0

for person in peopleArray {
    if person == "Novak" { break }
    positionOfNovak += 1
}

print("Novak is the element at position [\(positionOfNovak)] in peopleArray.")
// Novak is the element at position [5] in peopleArray. (zero-based index)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents