8. Break in Swift

Some time you need to break the loop on some point. You can break while loop as well as for loop by using ‘break’ statement.

Check following code, For loop will terminate when value of i will be 5

// Break Statement

for (var i=0; i <= 10; i++) {
    if i == 5{
        println("Loop is broken because i = \(i)")
        break
    }
    println("value of i  \(i)")
}

Check follwing code, While loop will terminate when value of k will be 7

// Break Statement

var k = 0
while k<=10 {
    if k == 7{
        println("Loop is broken because k = \(k)")
        break
    }
    println("value of k \(k)")
    k++;
}

Examine this in Console output, open View -> Assistant Editor -> Show Assistant Editor