Thuta Learning
IntermediateProgrammingbeginner

Functions

Relax. We'll talk through this in plain words — no textbook voice.

Functions are named, reusable blocks of code that perform a task. Using functions cuts down on duplicate code, makes testing easier, and lets you read your logic piece by piece.

swift
func calculateTotal(price: Int, quantity: Int) -> Int {
    return price * quantity
}

let total = calculateTotal(price: 1500, quantity: 2)
print("Total price: \(total)")

calculateTotal function takes price and quantity as its two parameters and returns an Int value. When you call the function, you need to write the argument labels price:, quantity:.

You should see
Total price: 3000

Easy traps

  • If a function is declared to return a value but you don't write a return statement, you'll get an error.
Functions | Thuta Learning