Control Flow
If-Else Statements
kode
if (condition) {
// executed when condition is true
} else if (otherCondition) {
// executed when otherCondition is true
} else {
// executed when all conditions are false
}
// Expression form (returns value)
let status = if (age >= 18) { "adult" } else { "minor" }Example
kode
let age = 18
if (age >= 18) {
print("You are an adult")
} else if (age >= 13) {
print("You are a teenager")
} else {
print("You are a child")
}While Loops
kode
while (count <= 5) {
print(count)
count = count + 1
}
// Do-while loop
do {
print(value)
value = value + 1
} while (value < 10)For Loops
C-style for loop
kode
for (let i = 0; i < 5; i = i + 1) {
print(i)
}
// 0 1 2 3 4For-in loop (iteration)
kode
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
print(fruit)
}
// apple
// banana
// cherryFor-each with index
kode
for (let i, item in collection) {
print("${i}: ${item}")
}Break and Continue
kode
for (let i = 0; i < 10; i = i + 1) {
if (i == 3) {
continue // Skip this iteration
}
if (i == 7) {
break // Exit loop
}
print(i)
}
// 0 1 2 4 5 6Match Expression
kode
let result = match (value) {
1 => "one",
2 => "two",
3 => "three",
_ => "other" // default case
}
// With complex patterns
match (pair) {
(0, y) => print("x is zero: ${y}"),
(x, 0) => print("y is zero: ${x}"),
(x, y) => print("both non-zero: ${x}, ${y}")
}