The break statement results in the termination of the loop, it will come out of the loop and stops further iterations.
var sum = 0;
for var i = 0 ; i < 5 ; i++ {
if i == 2 {
break //this ends the entire loop
}
sum += i //thus only 0 and 1 will be added
}
The continue statement stops the current execution of the iteration and proceeds to the next iteration.
var sum = 0;
for var i = 0 ; i < 5 ; i++ {
if i == 4 {
continue //this ends this iteration of the loop
}
sum += i //thus, 0, 1, 2, and 3 will be added to this, but not 4
}
The return statement takes you out of the method. It stops executing the method and returns from the method execution.
function returnMe() {
for (var i=0; i<2; i++) {
if (i === 1)
return i;
}
}
alert(returnMe());
// 1
func myMethod(){
newMethod()
}
func newMethod(){
var sum = 0;
sum += 2;
if sum > 1 {
return //jumps back to myMethod()
}
sum += 3; //this statement will never be executed
}
Returns can also be used to return a value from the function.
func myFunc() {
let value = newFunc() //assigns 5 to "value"
}
func newFunc() -> Int {
return 5
}
Top comments (0)