Skip to content

Functions

func takeDamage(amount: float) {
health -= amount
}
func divide(a: float, b: float) -> float {
return a / b
}

Void return can be implicit or explicit:

func doSomething() { }
func doSomething() -> void { }

Named and positional arguments both work at the call site:

damage(target: enemy, amount: 50.0) // named
damage(enemy, 50.0) // positional

Use ... to accept a variable number of arguments:

func sum(...numbers: int) -> int {
var total = 0
for n in numbers { total += n }
return total
}
sum(1, 2, 3, 4) // 10

class Player {
public static func create(name: string) -> Player {
return Player(name: name, health: 100.0)
}
}
let p = Player.create("Hero")

Parameter types required; return type is inferred.

let double = (x: int) => x * 2
let onDamage = (amount: float) => {
print("Took " .. amount .. " damage")
health -= amount
}

Lambdas can be reassigned when declared with var:

var handler = (amount: float) => {
print(amount)
}

return inside a lambda returns from the lambda only, never the enclosing function.

Lambdas capture variables from their enclosing scope by reference. Mutations are shared:

var count = 0
let increment = () => { count += 1 }
let getCount = () => count
increment()
increment()
print(getCount()) // 2

Multiple closures over the same variable see each other’s changes.