TExcelTAD
Home › Swift › Swift Exercises

Swift Exercises

Time to practise what you've learned! Each exercise gives you a starter program that already compiles and runs, but doesn't do the job yet. Edit the code in the playground, press ▶ Run, and compare your result with the expected output. Try on your own before opening the solution.

# Exercise Topics
1 Temperature table functions, String(format:)
2 FizzBuzz loops, switch, %
3 Vowel counter strings, Character, filter
4 Safe average optionals, guard
5 Word frequency dictionaries, sorting
6 Shapes protocols, structs
7 Bank withdrawal errors, throws/catch
8 Grade report map, filter, reduce

1. Temperature table

Complete fahrenheit(_:) using the formula F = C × 9 / 5 + 32, so the table shows the right values with one decimal place.

swift · try it yourself
import Foundation

func fahrenheit(_ celsius: Double) -> Double {
    // TODO: return the converted value
    return 0
}

for c in [-10.0, 0.0, 21.5, 100.0] {
    print(String(format: "%6.1f°C = %6.1f°F", c, fahrenheit(c)))
}
 -10.0°C =    0.0°F
   0.0°C =    0.0°F
  21.5°C =    0.0°F
 100.0°C =    0.0°F
Show solution
swift
import Foundation

func fahrenheit(_ celsius: Double) -> Double {
    celsius * 9 / 5 + 32
}

for c in [-10.0, 0.0, 21.5, 100.0] {
    print(String(format: "%6.1f°C = %6.1f°F", c, fahrenheit(c)))
}
text
 -10.0°C =   14.0°F
   0.0°C =   32.0°F
  21.5°C =   70.7°F
 100.0°C =  212.0°F

2. FizzBuzz

For the numbers 1 to 15 print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, otherwise the number. Use a switch on a tuple.

swift · try it yourself
for n in 1...15 {
    // TODO: replace with a switch on (n % 3, n % 5)
    print(n)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Show solution
swift
for n in 1...15 {
    switch (n % 3, n % 5) {
    case (0, 0): print("FizzBuzz")
    case (0, _): print("Fizz")
    case (_, 0): print("Buzz")
    default: print(n)
    }
}
text
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

3. Vowel counter

Make countVowels return how many vowels (a, e, i, o, u — upper or lower case) a sentence contains.

swift · try it yourself
func countVowels(in text: String) -> Int {
    // TODO
    return 0
}

for sentence in ["Hello, World", "Swift Is Awesome", "rhythm"] {
    print("\(sentence): \(countVowels(in: sentence))")
}
Hello, World: 0
Swift Is Awesome: 0
rhythm: 0
Show solution
swift
func countVowels(in text: String) -> Int {
    let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
    return text.lowercased().filter { vowels.contains($0) }.count
}

for sentence in ["Hello, World", "Swift Is Awesome", "rhythm"] {
    print("\(sentence): \(countVowels(in: sentence))")
}
text
Hello, World: 3
Swift Is Awesome: 6
rhythm: 0

4. Safe average

average should return nil for an empty array instead of dividing by zero. Change the return type to Double?, add a guard, and print "no data" when the result is nil.

swift · try it yourself
func average(_ values: [Double]) -> Double {
    // TODO: return nil for an empty array
    return values.reduce(0, +) / Double(values.count)
}

print(average([4, 8, 9]))
print(average([2.5, 3.5]))
7.0
3.0

Then add average([]) to the test calls — with the starter code it would print nan.

Show solution
swift
func average(_ values: [Double]) -> Double? {
    guard !values.isEmpty else { return nil }
    return values.reduce(0, +) / Double(values.count)
}

for data in [[4, 8, 9], [2.5, 3.5], []] {
    if let avg = average(data) {
        print(avg)
    } else {
        print("no data")
    }
}
text
7.0
3.0
no data

5. Word frequency

Count how often each word appears (ignoring case) and print the words sorted by count, highest first, then alphabetically for ties. Remember that dictionary order is random — you must sort.

swift · try it yourself
let text = "the cat and the dog and the bird"
var counts: [String: Int] = [:]

// TODO: fill `counts`, then print sorted lines like "the: 3"
print(text.split(separator: " ").count, "words")
8 words
Show solution
swift
let text = "the cat and the dog and the bird"
var counts: [String: Int] = [:]

for word in text.lowercased().split(separator: " ") {
    counts[String(word), default: 0] += 1
}

let sorted = counts.sorted { a, b in
    a.value != b.value ? a.value > b.value : a.key < b.key
}
for (word, count) in sorted {
    print("\(word): \(count)")
}
text
the: 3
and: 2
bird: 1
cat: 1
dog: 1

6. Shapes

Add a Rectangle struct and a Circle struct that conform to the Shape protocol, then print the total area of all shapes.

swift · try it yourself
import Foundation

protocol Shape {
    var name: String { get }
    func area() -> Double
}

let shapes: [Shape] = [
    // TODO: Rectangle(width: 3, height: 4), Circle(radius: 1)
]

print("Shapes:", shapes.count)
Shapes: 0
Show solution
swift
import Foundation

protocol Shape {
    var name: String { get }
    func area() -> Double
}

struct Rectangle: Shape {
    let width: Double, height: Double
    var name: String { "Rectangle" }
    func area() -> Double { width * height }
}

struct Circle: Shape {
    let radius: Double
    var name: String { "Circle" }
    func area() -> Double { Double.pi * radius * radius }
}

let shapes: [Shape] = [Rectangle(width: 3, height: 4), Circle(radius: 1)]

for shape in shapes {
    print(shape.name, String(format: "%.2f", shape.area()))
}
let total = shapes.reduce(0) { $0 + $1.area() }
print("Total:", String(format: "%.2f", total))
text
Rectangle 12.00
Circle 3.14
Total: 15.14

7. Bank withdrawal

Make withdraw throw an error instead of printing a message: BankError.insufficientFunds(needed:) when the balance is too low, and BankError.invalidAmount for amounts ≤ 0. Then call it with do/try/catch.

swift · try it yourself
enum BankError: Error {
    case invalidAmount
    case insufficientFunds(needed: Int)
}

var balance = 100

func withdraw(_ amount: Int) {
    // TODO: make this function throw
    if amount <= balance {
        balance -= amount
        print("Withdrew \(amount), balance \(balance)")
    } else {
        print("Not enough money")
    }
}

withdraw(30)
withdraw(500)
withdraw(-5)
Withdrew 30, balance 70
Not enough money
Withdrew -5, balance 75

The last line shows the bug: a negative withdrawal adds money!

Show solution
swift
enum BankError: Error {
    case invalidAmount
    case insufficientFunds(needed: Int)
}

var balance = 100

func withdraw(_ amount: Int) throws {
    guard amount > 0 else { throw BankError.invalidAmount }
    guard amount <= balance else {
        throw BankError.insufficientFunds(needed: amount - balance)
    }
    balance -= amount
    print("Withdrew \(amount), balance \(balance)")
}

for amount in [30, 500, -5] {
    do {
        try withdraw(amount)
    } catch BankError.insufficientFunds(let needed) {
        print("Need \(needed) more")
    } catch {
        print("Error: \(error)")
    }
}
text
Withdrew 30, balance 70
Need 430 more
Error: invalidAmount

8. Grade report

Use filter, map and reduce (no for loops!) to print: the names of students who passed (score ≥ 50) in alphabetical order, and the class average with one decimal place.

swift · try it yourself
import Foundation

let scores = ["Ana": 78, "Ben": 45, "Cara": 92, "Dan": 50, "Eve": 33]

// TODO: passed names, sorted; class average
print(scores.count, "students")
5 students
Show solution
swift
import Foundation

let scores = ["Ana": 78, "Ben": 45, "Cara": 92, "Dan": 50, "Eve": 33]

let passed = scores.filter { $0.value >= 50 }.map(\.key).sorted()
let average = Double(scores.values.reduce(0, +)) / Double(scores.count)

print("Passed:", passed.joined(separator: ", "))
print("Average:", String(format: "%.1f", average))
text
Passed: Ana, Cara, Dan
Average: 59.6

Test yourself

Why must the word-frequency results be sorted before printing?

  1. Dictionaries only store sorted keys
  2. Swift dictionary iteration order is not guaranteed
  3. print() requires sorted input
  4. To remove duplicate words

Which function signature lets callers use try on it?

  1. func withdraw(_ amount: Int) -> Error
  2. func withdraw(_ amount: Int) throws
  3. func withdraw(_ amount: Int) async
  4. func withdraw(_ amount: Int) rethrows -> Never