9

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?

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
George Lee
  • 814
  • 18
  • 34

1 Answers1

10

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.

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
  • 1
    Actually, completely removing `break` wouldn't make a difference in the OP's code. That `break` is only an performance improvement. – Sulthan Dec 31 '15 at 13:58
  • Removing break statement will reflect in output. @Sulthan Then output should be like `[3, 9, 44, 52, 78, 6, 22, 91, 35]` – Ashish Kakkad Jan 13 '16 at 07:06