Control Flow
If / Else
wyn
score = 85
if score >= 90 {
print("A grade")
} else if score >= 80 {
print("B grade")
} else {
print("Try harder")
}For Loops
Range
wyn
for i in 0..5 {
print("Count: ${i}")
}Over Arrays
wyn
fruits = ["apple", "banana", "orange"]
for fruit in fruits {
print("Fruit: ${fruit}")
}Indexed Iteration
Access both the index and value with for i, v in arr:
wyn
names = ["Alice", "Bob", "Charlie"]
for i, name in names {
print(i.to_string() + ": " + name)
}
// 0: Alice
// 1: Bob
// 2: CharlieOver Maps
Iterate a HashMap directly. Bind both key and value with for k, v in map, or just the keys with for k in map:
wyn
scores = {"alice": 90, "bob": 85}
for name, score in scores {
print("${name}: ${score}")
}
for name in scores {
print(name)
}Membership: in / not in
Test membership with in and not in. It works on arrays (element), strings (substring), and maps (key):
wyn
nums = [1, 2, 3]
if 2 in nums { print("has 2") }
if 5 not in nums { print("no 5") }
if "ell" in "hello" { print("substring") }
config = {"debug": "on"}
if "debug" in config { print("debug is set") }in sits at comparison precedence, so it reads naturally inside if and while conditions. (The in of a for … in … loop is unaffected.)
While Loops
wyn
count = 0
while count < 3 {
print("Count: ${count}")
count = count + 1
}Break and Continue
wyn
for i in 0..100 {
if i == 5 { break }
if i % 2 == 0 { continue }
print(i.to_string())
}Try It
Press Run or Ctrl+Enter
See Also
- Pattern Matching -
matchwith destructuring - Arrays - array methods for
for-inloops - Spawn & Await - concurrent loops