Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is breaking out of an outer loop still applicable in Swift 2?

I am reading the book, Professional Swift by Michael Dippery @ 2015. And in the book, on page 25, he writes:

"Both break and continue statements break out of the innermost loops. However, you can label loops, which enables you to break out of an outer loop instead"

let data = [[3,9,44],[52,78,6],[22,91,35]]
let searchFor = 78
var foundVal = false

outer: for ints in data {
    inner: for val in ints {
        if val == searchFor {
            foundVal = true
            break outer
        }
    }
}

if foundVal {
    print("Found \(searchFor) in \(data)")
} else {
    print("Could not find \(searchFor) in \(data)")
}

however, in playground when I change:

break outer 

code to

break inner

The same result occurs:

Found 78 in [[3, 9, 44], [52, 78, 6], [22, 91, 35]]

Is it still necessary to label loops to break out of an outer loop?

like image 521
George Lee Avatar asked Dec 30 '15 04:12

George Lee


1 Answers

Breaking inner and outer loop make difference lets check again with your code by taking one updatedData variable.

let data = [[3,9,44],[52,78,6],[22,91,35]]
let searchFor = 78
var updatedData = [Int]()
var foundVal = false

outer: for ints in data {
    inner: for val in ints {
        updatedData.append(val)
        if val == searchFor {
            foundVal = true
            break outer
        }
    }
}

In break outer you will get like :

Found 78 in [[3, 9, 44], [52, 78, 6], [22, 91, 35]]

updated data is [3, 9, 44, 52, 78]

In break inner you will get different updated data :

Found 78 in [[3, 9, 44], [52, 78, 6], [22, 91, 35]]

updated data is [3, 9, 44, 52, 78, 22, 91, 35]

So, you will check that in break inner after the 78 the 6 is not added to the updated data because inner loop is only breaked and again it stared with the next ints.

In break outer the whole loop will be breked.

Hope you will get help from this.

like image 75
Ashish Kakkad Avatar answered Nov 18 '22 03:11

Ashish Kakkad