Skip to content
AgileLogics
6 min read

Functions

Prerequisites: Arrays

A function is a named, reusable block of code that performs a task. You write it once and call it whenever you need it.

Real-world analogy: a function is a recipe. You write the steps once, then just say "make pancakes" whenever you want them.

Syntax

func name(parameter: Type) -> ReturnType {
    // code
    return value
}

Example

func greet(person: String) -> String {
    return "Hello, \(person)!"
}

print(greet(person: "Ada"))
print(greet(person: "Linus"))

Expected output

Hello, Ada!
Hello, Linus!

Line by line:

  • func greet(person: String) defines a function with one parameter, person, which must be a String.
  • -> String says the function returns a String.
  • return sends the result back to the caller.
  • When calling it, you write the parameter's name as a label: greet(person: "Ada"). Labels make calls read clearly.

If the body is a single expression, return can be left out:

func square(_ n: Int) -> Int {
    n * n
}
print(square(7))
49

(The _ means "no label at the call site" — the next lesson explains labels in detail.)

Functions without a return value

Leave out the -> part:

func printBanner(_ text: String) {
    print("*** \(text) ***")
}

printBanner("Sale")
*** Sale ***

Common mistakes

  • Forgetting the label: greet("Ada") gives missing argument label 'person:' in call.
  • Declaring a return type but not returning a value on every path: missing return in global function expected to return 'String'.

Practice

Write area(width:height:) returning the area of a rectangle as a Double, and isSquare(width:height:) returning a Bool. Print both for a 4 by 4 rectangle.

Show solution
func area(width: Double, height: Double) -> Double {
    width * height
}

func isSquare(width: Double, height: Double) -> Bool {
    width == height
}

print(area(width: 4, height: 4))
print(isSquare(width: 4, height: 4))
16.0
true