#07: Labeled statements in Swift
Suppose you have something like the series of nested loops shown below, and you need a way to break out of these loop when a certain condition arises:
var array = [1,2,3,-1,5]
var a = 5
outer: for j in 0...3{
while a>0 {
inner: for i in 0..<array.count {
if array[i] < 0 {
//Exit prematurely!
}
}
a = a-1
}
}
a //0
Swift provides labeled statement that can be applied to flow control elements (conditional or loop statements like if, for, while and repeat-while) and can be used as a location specifier for continue
and break
.
To create a label, simply add a string followed by colon before the statement it will refer to.
In the example above, if we’d wanted to complete prematurely the main for loop (outer) we would have added the following line:
if array[i] < 0 {
//Exit prematurely!
break outer
}
}
a = a-1
}
}
a //5
This feature should not be abused, but sometimes it can come in handy.
Did you like this article? Let me know on Twitter or subscribe for updates!