Functions
Named functions
Section titled “Named 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 { }Arguments
Section titled “Arguments”Named and positional arguments both work at the call site:
damage(target: enemy, amount: 50.0) // nameddamage(enemy, 50.0) // positionalVariadic parameters
Section titled “Variadic parameters”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) // 10Static methods
Section titled “Static methods”class Player { public static func create(name: string) -> Player { return Player(name: name, health: 100.0) }}
let p = Player.create("Hero")Lambdas
Section titled “Lambdas”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.
Closures
Section titled “Closures”Lambdas capture variables from their enclosing scope by reference. Mutations are shared:
var count = 0let increment = () => { count += 1 }let getCount = () => count
increment()increment()print(getCount()) // 2Multiple closures over the same variable see each other’s changes.