-
Notifications
You must be signed in to change notification settings - Fork 2
Control Flow
Argon provides a variety of control flow statements. These include C-style for, for-in and loop loops to perform task multiple times, if and switch statements to execute different branches of code based on certain conditions, and statements like break and continue to transfer the flow of execution to another point in the code.
You use the for-in loop to iterate over a sequence, such as items in an array or set.
This example uses a for-in loop to iterate over the items in an array:
let NOBLE_GAS = ["Helium", "Neon", "Argon", "Krypton", "Xenon"]
var gas
for gas in NOBLE_GAS {
println(gas)
}
# Helium
# Neon
# Argon
# Krypton
# Xenon
A loop loops performs a set of statement until a condition becomes false, or until an explicit break statement not being reached (loop without condition). These kind of loops are best used when number of iteration is not known before the first iteration begins.
A loop loop starts by evalutating a single condition, if the condition is true, a set of statements is repeated until the condition becomes false.
loop condition {
statements
}
var i = 0
loop i < 5 {
println(i++)
}
A loop loop without a condition is a infinite loop, you can exit from infinite loop with break keyword.
var i = 0
loop {
println(i++)
if i >= 5 {
break
}
}
It is often useful to execute different pieces of code based on certain conditions. You might want to run an extra piece of code when an error occurs, or to display a message when a value is reached. To do this, you need to use a condition. Argon provides two ways to add conditional branches to your code, the if statement and the switch statement. Typically, you use the if to evalutate simple condition with few possibile outcomes, instead switch statement is better suited to more complex condition with multiple possible permutations.
In its simplets form, the if statement has a single condition. It executes the body statements only if the condition is true.
var pm10 = 51
if pm10 > 50 { println("exceeded the PM10 daily limit") }
Obviously, if statement can provide an alternative set of statements, known as an else clause, for situations when the if condition is false.
var pm10 = 36
if pm10 > 50 {
println("exceeded the PM10 daily limit")
} else {
println("PM10 within the allowed limits")
}
You also can chain multiple if statements together to consider additional clauses.
var pm10 = 36
if pm10 > 50 {
println("exceeded the PM10 daily limit")
} elif pm10 == 50 {
println("PM10 Pm10 at the allowed limit.")
} else {
println("PM10 within the allowed limits")
}
Remember: the final else clause is always optional!