Control Flow

Control flow statements control the flow of execution in a function.

Conditional branching: if-statement

If-statements allow a certain piece of code to be executed only when a given condition is true.

The if-statement starts with the if keyword, followed by the condition, and the code that should be executed if the condition is true inside opening and closing braces. The condition expression must be boolean. The braces are required and not optional. Parentheses around the condition are optional.

1
let a = 0
2
var b = 0
3
4
if a == 0 {
5
b = 1
6
}
7
8
// Parentheses can be used around the condition, but are not required.
9
if (a != 0) {
10
b = 2
11
}
12
13
// `b` is `1`

An additional, optional else-clause can be added to execute another piece of code when the condition is false. The else-clause is introduced by the else keyword followed by braces that contain the code that should be executed.

1
let a = 0
2
var b = 0
3
4
if a == 1 {
5
b = 1
6
} else {
7
b = 2
8
}
9
10
// `b` is `2`

The else-clause can contain another if-statement, i.e., if-statements can be chained together. In this case the braces can be omitted.

1
let a = 0
2
var b = 0
3
4
if a == 1 {
5
b = 1
6
} else if a == 2 {
7
b = 2
8
} else {
9
b = 3
10
}
11
12
// `b` is `3`
13
14
if a == 1 {
15
b = 1
16
} else {
17
if a == 0 {
18
b = 2
19
}
20
}
21
22
// `b` is `2`

Optional Binding

Optional binding allows getting the value inside an optional. It is a variant of the if-statement.

If the optional contains a value, the first branch is executed and a temporary constant or variable is declared and set to the value contained in the optional; otherwise, the else branch (if any) is executed.

Optional bindings are declared using the if keyword like an if-statement, but instead of the boolean test value, it is followed by the let or var keywords, to either introduce a constant or variable, followed by a name, the equal sign (=), and the optional value.

1
let maybeNumber: Int? = 1
2
3
if let number = maybeNumber {
4
// This branch is executed as `maybeNumber` is not `nil`.
5
// The constant `number` is `1` and has type `Int`.
6
} else {
7
// This branch is *not* executed as `maybeNumber` is not `nil`
8
}
1
let noNumber: Int? = nil
2
3
if let number = noNumber {
4
// This branch is *not* executed as `noNumber` is `nil`.
5
} else {
6
// This branch is executed as `noNumber` is `nil`.
7
// The constant `number` is *not* available.
8
}

Switch

Switch-statements compare a value against several possible values of the same type, in order. When an equal value is found, the associated block of code is executed.

The switch-statement starts with the switch keyword, followed by the tested value, followed by the cases inside opening and closing braces. The test expression must be equatable. The braces are required and not optional.

Each case is a separate branch of code execution and starts with the case keyword, followed by a possible value, a colon (:), and the block of code that should be executed if the case's value is equal to the tested value.

The block of code associated with a switch case does not implicitly fall through, and must contain at least one statement. Empty blocks are invalid.

An optional default case may be given by using the default keyword. The block of code of the default case is executed when none of the previous case tests succeeded. It must always appear last.

1
fun word(_ n: Int): String {
2
// Test the value of the parameter `n`
3
switch n {
4
case 1:
5
// If the value of variable `n` is equal to `1`,
6
// then return the string "one"
7
return "one"
8
case 2:
9
// If the value of variable `n` is equal to `2`,
10
// then return the string "two"
11
return "two"
12
default:
13
// If the value of variable `n` is neither equal to `1` nor to `2`,
14
// then return the string "other"
15
return "other"
16
}
17
}
18
19
word(1) // returns "one"
20
word(2) // returns "two"
21
word(3) // returns "other"
22
word(4) // returns "other"

Duplicate cases

Cases are tested in order, so if a case is duplicated, the block of code associated with the first case that succeeds is executed.

1
fun test(_ n: Int): String {
2
// Test the value of the parameter `n`
3
switch n {
4
case 1:
5
// If the value of variable `n` is equal to `1`,
6
// then return the string "one"
7
return "one"
8
case 1:
9
// If the value of variable `n` is equal to `1`,
10
// then return the string "also one".
11
// This is a duplicate case for the one above.
12
return "also one"
13
default:
14
// If the value of variable `n` is neither equal to `1` nor to `2`,
15
// then return the string "other"
16
return "other"
17
}
18
}
19
20
word(1) // returns "one", not "also one"

break

The block of code associated with a switch case may contain a break statement. It ends the execution of the switch statement immediately and transfers control to the code after the switch statement

No Implicit Fallthrough

Unlike switch statements in some other languages, switch statements in Cadence do not "fall through": execution of the switch statement finishes as soon as the block of code associated with the first matching case is completed. No explicit break statement is required.

This makes the switch statement safer and easier to use, avoiding the accidental execution of more than one switch case.

Some other languages implicitly fall through to the block of code associated with the next case, so it is common to write cases with an empty block to handle multiple values in the same way.

To prevent developers from writing switch statements that assume this behaviour, blocks must have at least one statement. Empty blocks are invalid.

1
fun words(_ n: Int): [String] {
2
// Declare a variable named `result`, an array of strings,
3
// which stores the result
4
let result: [String] = []
5
6
// Test the value of the parameter `n`
7
switch n {
8
case 1:
9
// If the value of variable `n` is equal to `1`,
10
// then append the string "one" to the result array
11
result.append("one")
12
case 2:
13
// If the value of variable `n` is equal to `2`,
14
// then append the string "two" to the result array
15
result.append("two")
16
default:
17
// If the value of variable `n` is neither equal to `1` nor to `2`,
18
// then append the string "other" to the result array
19
result.append("other")
20
}
21
return result
22
}
23
24
words(1) // returns `["one"]`
25
words(2) // returns `["two"]`
26
words(3) // returns `["other"]`
27
words(4) // returns `["other"]`

Looping

while-statement

While-statements allow a certain piece of code to be executed repeatedly, as long as a condition remains true.

The while-statement starts with the while keyword, followed by the condition, and the code that should be repeatedly executed if the condition is true inside opening and closing braces. The condition must be boolean and the braces are required.

The while-statement will first evaluate the condition. If it is true, the piece of code is executed and the evaluation of the condition is repeated. If the condition is false, the piece of code is not executed and the execution of the whole while-statement is finished. Thus, the piece of code is executed zero or more times.

1
var a = 0
2
while a < 5 {
3
a = a + 1
4
}
5
6
// `a` is `5`

For-in statement

For-in statements allow a certain piece of code to be executed repeatedly for each element in an array.

The for-in statement starts with the for keyword, followed by the name of the element that is used in each iteration of the loop, followed by the in keyword, and then followed by the array that is being iterated through in the loop.

Then, the code that should be repeatedly executed in each iteration of the loop is enclosed in curly braces.

If there are no elements in the data structure, the code in the loop will not be executed at all. Otherwise, the code will execute as many times as there are elements in the array.

1
let array = ["Hello", "World", "Foo", "Bar"]
2
3
for element in array {
4
log(element)
5
}
6
7
// The loop would log:
8
// "Hello"
9
// "World"
10
// "Foo"
11
// "Bar"

Optionally, developers may include an additional variable preceding the element name, separated by a comma. When present, this variable contains the current index of the array being iterated through during each repeated execution (starting from 0).

1
let array = ["Hello", "World", "Foo", "Bar"]
2
3
for index, element in array {
4
log(index)
5
}
6
7
// The loop would log:
8
// 0
9
// 1
10
// 2
11
// 3

To iterate over a dictionary's entries (keys and values), use a for-in loop over the dictionary's keys and get the value for each key:

1
let dictionary = {"one": 1, "two": 2}
2
for key in dictionary.keys {
3
let value = dictionary[key]!
4
log(key)
5
log(value)
6
}
7
8
// The loop would log:
9
// "one"
10
// 1
11
// "two"
12
// 2

continue and break

In for-loops and while-loops, the continue statement can be used to stop the current iteration of a loop and start the next iteration.

1
var i = 0
2
var x = 0
3
while i < 10 {
4
i = i + 1
5
if i < 3 {
6
continue
7
}
8
x = x + 1
9
}
10
// `x` is `8`
11
12
13
let array = [2, 2, 3]
14
var sum = 0
15
for element in array {
16
if element == 2 {
17
continue
18
}
19
sum = sum + element
20
}
21
22
// `sum` is `3`

The break statement can be used to stop the execution of a for-loop or a while-loop.

1
var x = 0
2
while x < 10 {
3
x = x + 1
4
if x == 5 {
5
break
6
}
7
}
8
// `x` is `5`
9
10
11
let array = [1, 2, 3]
12
var sum = 0
13
for element in array {
14
if element == 2 {
15
break
16
}
17
sum = sum + element
18
}
19
20
// `sum` is `1`

Immediate function return: return-statement

The return-statement causes a function to return immediately, i.e., any code after the return-statement is not executed. The return-statement starts with the return keyword and is followed by an optional expression that should be the return value of the function call.