SwSwift

Swift exercises with solutions

Solve in editor

Write your solution right in the browser.

Open exercises with editor

1. Even numbers Beginner

Print all even numbers from 1 to 10, each on its own line.

Expected output: 2 ⏎ 4 ⏎ 6 ⏎ 8 ⏎ 10

Note

stride(from: 2, through: 10, by: 2) jumps in steps of two. Or check with i % 2 == 0.

Show sample solution
for i in stride(from: 2, through: 10, by: 2) {
    print(i)
}

2. FizzBuzz (1–15) Beginner

Print the numbers 1 to 15. For multiples of 3 print Fizz instead, for multiples of 5 print Buzz, and for both print FizzBuzz.

Expected output: 1 ⏎ 2 ⏎ Fizz ⏎ 4 ⏎ Buzz ⏎ Fizz ⏎ 7 ⏎ 8 ⏎ Fizz ⏎ Buzz ⏎ 11 ⏎ Fizz ⏎ 13 ⏎ 14 ⏎ FizzBuzz

Note

switch (i % 3, i % 5) with the cases (0, 0), (0, _), (_, 0), and default is elegant.

Show sample solution
for i in 1...15 {
    switch (i % 3, i % 5) {
    case (0, 0): print("FizzBuzz")
    case (0, _): print("Fizz")
    case (_, 0): print("Buzz")
    default: print(i)
    }
}

3. Reverse a word Beginner

Reverse the string "Swift" and print it.

Expected output: tfiwS

Note

reversed() returns a reversed sequence of characters; with String(...) you turn it back into a string.

Show sample solution
let wort = "Swift"
print(String(wort.reversed()))

4. Sum of squares Beginner

Calculate the sum of the squares of the numbers 1 to 10 and print it.

Expected output: 385

Note

Range 1...10, then map { $0 * $0 } and reduce(0, +).

Show sample solution
print((1...10).map { $0 * $0 }.reduce(0, +))

5. Palindrome function Intermediate

Write a function istPalindrom(_ text: String) -> Bool that returns true if the text reads the same forwards and backwards (ignoring case). Print istPalindrom("Anna") and istPalindrom("Swift").

Expected output: true ⏎ false

Note

First convert with lowercased() and compare the text with String(t.reversed()).

Show sample solution
func istPalindrom(_ text: String) -> Bool {
    let t = text.lowercased()
    return t == String(t.reversed())
}

print(istPalindrom("Anna"))
print(istPalindrom("Swift"))

6. Most frequent word Intermediate

Find the most frequent word in "a b a c b a" and print it.

Expected output: a

Note

Count with a dictionary (zaehler[wort, default: 0] += 1) and find the maximum with max(by:) over the values.

Show sample solution
let text = "a b a c b a"
var zaehler: [String: Int] = [:]
for wort in text.split(separator: " ") {
    zaehler[String(wort), default: 0] += 1
}
if let beste = zaehler.max(by: { $0.value < $1.value }) {
    print(beste.key)
}

7. Shapes with a protocol Intermediate

Define a protocol Form with func flaeche() -> Double and two structs Rechteck (breite, hoehe) and Quadrat (seite) that conform to it. Put a 3x4 rectangle and a square with side 2 into an array [any Form] and print the sum of the areas.

Expected output: 16.0

Note

let formen: [any Form] = [Rechteck(breite: 3, hoehe: 4), Quadrat(seite: 2)] and then formen.map { $0.flaeche() }.reduce(0, +). A Double with the value 16 is printed as 16.0.

Show sample solution
protocol Form {
    func flaeche() -> Double
}

struct Rechteck: Form {
    let breite: Double
    let hoehe: Double
    func flaeche() -> Double { breite * hoehe }
}

struct Quadrat: Form {
    let seite: Double
    func flaeche() -> Double { seite * seite }
}

let formen: [any Form] = [Rechteck(breite: 3, hoehe: 4), Quadrat(seite: 2)]
print(formen.map { $0.flaeche() }.reduce(0, +))

8. Parallel sum Advanced

As a script, calculate the sum 1 to 100 with four parallel tasks: task i (0 to 3) sums the numbers from i*25+1 to (i+1)*25. Collect the partial sums in a TaskGroup, add them up, and print the result.

Expected output: 5050

Note

await withTaskGroup(of: Int.self) { gruppe in ... }: start with gruppe.addTask { ... }, collect with for await teil in gruppe, and return the sum.

Show sample solution
let gesamt = await withTaskGroup(of: Int.self) { gruppe in
    for i in 0..<4 {
        gruppe.addTask { ((i * 25 + 1)...((i + 1) * 25)).reduce(0, +) }
    }
    var summe = 0
    for await teil in gruppe { summe += teil }
    return summe
}
print(gesamt)