在 Swift 2 中是否仍然适用打破外循环?
Is breaking out of an outer loop still applicable in Swift 2?
我正在阅读 Michael Dippery 于 2015 年撰写的 Professional Swift 一书。在书中的第 25 页,他写道:
"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)")
}
然而,在操场上我改变的时候:
break outer
编码为
break inner
出现同样的结果:
找到78 in [[3, 9, 44], [52, 78, 6], [22, 91, 35]]
还需要label loops
突破outer loop
吗?
打破内循环和外循环会有所不同让我们通过取一个 updatedData
变量再次检查您的代码。
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
}
}
}
在 break outer
你会喜欢 :
Found 78 in [[3, 9, 44], [52, 78, 6], [22, 91, 35]]
updated data is [3, 9, 44, 52, 78]
在break inner
你会得到不同的更新数据:
Found 78 in [[3, 9, 44], [52, 78, 6], [22, 91, 35]]
updated data is [3, 9, 44, 52, 78, 22, 91, 35]
因此,您将检查在 78 之后的内部中断中,6 没有添加到更新的数据中,因为内部循环只是被中断,并且它再次盯着下一个 ints
。
在 break outer 中,整个循环将被中断。
希望您能从中得到帮助。
我正在阅读 Michael Dippery 于 2015 年撰写的 Professional Swift 一书。在书中的第 25 页,他写道:
"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)")
}
然而,在操场上我改变的时候:
break outer
编码为
break inner
出现同样的结果:
找到78 in [[3, 9, 44], [52, 78, 6], [22, 91, 35]]
还需要label loops
突破outer loop
吗?
打破内循环和外循环会有所不同让我们通过取一个 updatedData
变量再次检查您的代码。
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
}
}
}
在 break outer
你会喜欢 :
Found 78 in [[3, 9, 44], [52, 78, 6], [22, 91, 35]]
updated data is [3, 9, 44, 52, 78]
在break inner
你会得到不同的更新数据:
Found 78 in [[3, 9, 44], [52, 78, 6], [22, 91, 35]]
updated data is [3, 9, 44, 52, 78, 22, 91, 35]
因此,您将检查在 78 之后的内部中断中,6 没有添加到更新的数据中,因为内部循环只是被中断,并且它再次盯着下一个 ints
。
在 break outer 中,整个循环将被中断。
希望您能从中得到帮助。