Learn/Swift/6. Functions
Lesson 6 of 8
Sign in

Swift, lesson 6

Functions

As programs grow, you start repeating yourself. A function gives a name to a piece of work so you can run it whenever you need it, with different inputs each time. Good function names also make code read like a description of what it does.

Defining and calling a function

The parts are: the keyword func, the name, the parameters in parentheses (each with a name and a type), then -> and the return type. return hands a value back to whoever called the function. A function that returns nothing simply leaves out the arrow.

When the whole body is a single expression, you can drop the word return:

Argument labels

Swift functions read like sentences at the call site. Every parameter has an argument label (used when calling) and a parameter name (used inside the body). Normally they are the same, but you can give them different names, or replace the label with _ to leave it out:

2 exercises to try what you just read.

Exercise 1

Letter grades

Press Ctrl Enter or Check to test your code.

Exercise 2

Race clock

Press Ctrl Enter or Check to test your code.

Inside distance you use start and end; callers write from: and to:. This is why you had to write separator: when calling print.

Default values

A parameter can have a default value. Callers may then skip it:

Returning more than one value

To hand back several values at once, return a tuple. You can name its parts, which makes the caller's code clear:

Scope

A name declared inside a function's braces is local: it exists only while that function runs, and code outside cannot see it. That is a good thing, because two functions can each use a variable called count without stepping on each other.

Parameters are constants. If you try bill += 1 inside tip, the compiler stops you. Copy the value into a local var when you need to change it:

In this lesson's exercises a hidden part of the program reads the input and calls your function, so you only need to write the function itself.

Further reading

  • Functions
  • The Basics: tuples

Write a function grade(for score: Int) -> String that turns a test score into a letter:

ScoreLetter
90 and upA
80 to 89B
70 to 79C
60 to 69D
below 60F

A hidden program reads one score per line and prints grade(for: score) for each, so you only write the function.

Sample input:

Sample output:

Write a function clock(_ totalSeconds: Int) -> String that formats a race time given in seconds as minutes:seconds. The seconds part always has two digits; the minutes part has no padding. For example 125 becomes 2:05 and 3600 becomes 60:00.

A good plan is a helper function that returns a tuple (minutes: Int, seconds: Int), then building the text in clock. Add a leading "0" when the seconds are below 10.

A hidden program reads one number of seconds (0 or more) per line and prints clock(n).

Sample input:

Sample output:

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

print(greet(person: "Mia"))   // Hello, Mia!
func square(_ n: Int) -> Int {
    n * n
}
func distance(from start: Int, to end: Int) -> Int {
    end - start
}

print(distance(from: 3, to: 10))   // 7
print(square(4))                   // 16, no label because of _
func tip(on bill: Double, percent: Double = 15) -> Double {
    bill * percent / 100
}

print(tip(on: 40))               // 6.0
print(tip(on: 40, percent: 20))  // 8.0
func minutesAndSeconds(_ total: Int) -> (minutes: Int, seconds: Int) {
    (total / 60, total % 60)
}

let time = minutesAndSeconds(135)
print(time.minutes, time.seconds)   // 2 15
func countdown(from start: Int) {
    var n = start
    while n > 0 {
        print(n)
        n -= 1
    }
}
95
72
41
A
C
F
125
59
2:05
0:59