Swift143 exercises

Swift Exercises with Answers

Practise Swift with 143 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.

Score0/ 143

1Introduction

Read the lesson
Fill in the blankseasyIntroduction

Complete the line so it shows Hi in the console.

("Hi")
Predict the outputeasyIntroduction

What does this print?

print("A", "B", "C", separator: "")
Predict the outputmediumIntroduction

What does this print?

print("2 + 2")
print(2 + 2)
Multiple choicemediumIntroduction

Which file extension do Swift source files use?

Multiple choicehardIntroduction

Which tool is used to build and publish iPhone apps?

2Variables & Constants

Read the lesson
Fill in the blankseasyVariables & Constants

Complete the declaration so the value can never change.

 maxPlayers = 4
Predict the outputeasyVariables & Constants

What type does Swift infer for let x = 4.0?

Predict the outputmediumVariables & Constants

What does this print?

var a = 5
let b = a
a = 9
print(b)
Multiple choicemediumVariables & Constants

Which line correctly multiplies an Int count by 2.5?

Multiple choicehardVariables & Constants

What type does Int("abc") produce?

3Numbers & Operators

Read the lesson
Fill in the blankseasyNumbers & Operators

Complete the code so it shows the remainder of 17 divided by 5.

print(17  5)
Predict the outputeasyNumbers & Operators

What does print(9 / 2) show?

Predict the outputmediumNumbers & Operators

What does this print?

var x = 10
x -= 3
x *= 2
print(x)
Multiple choicemediumNumbers & Operators

How do you add one to a variable in Swift?

Multiple choicehardNumbers & Operators

What happens if an Int calculation goes past Int's maximum value?

Fill in the blankseasyStrings

Complete the interpolation so it prints "Hello, Ada".

let name = "Ada"
print("Hello, ")
Predict the outputeasyStrings

What does print("Swift".count) show?

Predict the outputmediumStrings

What does this print?

print("banana".prefix(3), "banana".suffix(2))
Multiple choicemediumStrings

Why can't you write text[2] to read a character in Swift?

Predict the outputhardStrings

What does this print?

let words = "a b c".split(separator: " ")
print(words.joined(separator: ""))
Fill in the blankseasyOptionals

Complete the declaration so middleName can be nil.

var middleName: String = nil
Predict the outputeasyOptionals

What does this print?

let city: String? = nil
print(city ?? "Unknown")
Predict the outputmediumOptionals

What does this print?

let word: String? = "swift"
print(word?.uppercased().count ?? 0)
Multiple choicemediumOptionals

What must the else block of a guard let do?

Multiple choicehardOptionals

When is force unwrapping with ! reasonable?

6if & switch

Read the lesson
Fill in the blankseasyif & switch

Complete the ternary so label is "Even" or "Odd".

let label = n % 2 == 0  "Even" : "Odd"
Predict the outputeasyif & switch

What does this print?

let x = 7
switch x {
case 1, 3, 5, 7, 9: print("odd")
default: print("even")
}
Predict the outputmediumif & switch

What does this print?

let t = 18
if t > 25 { print("hot") } else if t > 15 { print("mild") } else if t > 5 { print("cool") }
Multiple choicemediumif & switch

Which case matches every number from 10 up to, but not including, 20?

Multiple choicehardif & switch

What does case let (x, y) where x > y: do?

Fill in the blankseasyLoops

Complete the loop so it runs for 0, 1, 2 and 3.

for i in 04 { print(i) }
Predict the outputeasyLoops

How many times does for _ in 1...3 { } run?

Predict the outputmediumLoops

What does this print?

for x in stride(from: 1, to: 10, by: 3) { print(x, terminator: " ") }
Multiple choicemediumLoops

Which loop always runs its body at least once?

Predict the outputhardLoops

What does this print?

var total = 0
for n in 1...6 where n != 4 {
    total += n
}
print(total)
Fill in the blankseasyFunctions

Complete the declaration so the function can be called as square(4).

func square( n: Int) -> Int { n * n }
Predict the outputeasyFunctions

What does this print?

func greet(_ name: String = "friend") -> String { "Hi, \(name)" }
print(greet())
Predict the outputmediumFunctions

What does this print?

func total(_ xs: Int...) -> Int { xs.reduce(0, +) }
print(total(1, 2, 3, 4))
Multiple choicemediumFunctions

How do you call func move(from start: String, to end: String)?

Multiple choicehardFunctions

What does an inout parameter allow?

Fill in the blankseasyArrays

Complete the code so "eggs" is added to the end of the basket.

var basket = ["bread"]
basket.("eggs")
Predict the outputeasyArrays

What does this print?

let xs = ["a", "b", "c", "d"]
print(xs[2])
Predict the outputmediumArrays

What does this print?

var xs = [5, 3, 8]
xs.insert(1, at: 0)
xs.remove(at: 2)
print(xs)
Multiple choicemediumArrays

What's the difference between sort() and sorted()?

Predict the outputhardArrays

What does this print?

var a = [1, 2]
var b = a
b.append(3)
print(a.count, b.count)

10Dictionaries & Sets

Read the lesson
Fill in the blankseasyDictionaries & Sets

Complete the code so it reads the count for "cat", or 0 if it isn't there.

let n = counts["cat", : 0]
Predict the outputeasyDictionaries & Sets

What does this print?

let d = ["a": 1, "b": 2]
print(d["c"] ?? -1)
Predict the outputmediumDictionaries & Sets

What does this print?

var s: Set = [1, 2, 3]
s.insert(2)
s.insert(4)
print(s.count)
Multiple choicemediumDictionaries & Sets

How do you remove the key "cake" from a dictionary?

Multiple choicehardDictionaries & Sets

Why should you sort keys before printing a dictionary in a test?

Fill in the blankseasyClosures

Complete the code so every price is doubled.

let doubled = prices. { $0 * 2 }
Predict the outputeasyClosures

What does this print?

print([1, 2, 3, 4].filter { $0 % 2 == 0 })
Predict the outputmediumClosures

What does this print?

print([2, 3, 4].reduce(1, *))
Multiple choicemediumClosures

What does $0 mean inside a closure?

Multiple choicehardClosures

When must a closure parameter be marked @escaping?

Fill in the blankseasyStructs

Complete the method so it can change the struct's property.

struct Counter {
    var count = 0
     func reset() { count = 0 }
}
Predict the outputeasyStructs

What does this print?

struct Box { var w: Int; var h: Int; var area: Int { w * h } }
print(Box(w: 3, h: 4).area)
Predict the outputmediumStructs

What does this print?

struct P { var x: Int }
var a = P(x: 1)
var b = a
b.x = 5
print(a.x + b.x)
Multiple choicemediumStructs

What does init? mean?

Multiple choicehardStructs

When does Apple recommend using a struct instead of a class?

Fill in the blankseasyClasses

Complete the subclass method so it replaces the parent's version.

class Cat: Animal {
     func sound() -> String { "Meow" }
}
Multiple choiceeasyClasses

What kind of type is a class?

Predict the outputmediumClasses

What does this print?

class Box { var n = 1 }
let a = Box()
let b = a
b.n = 7
print(a.n)
Multiple choicemediumClasses

What does === check?

Multiple choicehardClasses

Why can you call a method that changes properties on a let class instance?

Fill in the blankseasyEnums

Complete the declaration so the enum gets an allCases list.

enum Weekday:  {
    case mon, tue, wed, thu, fri
}
Predict the outputeasyEnums

What does this print?

enum Coin: Int { case penny = 1, nickel = 5, dime = 10 }
print(Coin.dime.rawValue)
Multiple choicemediumEnums

What type does Size(rawValue: "XL") return?

Predict the outputmediumEnums

What does this print?

enum Shape { case circle(r: Double), square(side: Double) }
let s = Shape.square(side: 3)
switch s {
case .circle(let r): print(3.14 * r * r)
case .square(let side): print(side * side)
}
Multiple choicehardEnums

Why avoid default when switching over your own enum?

15Protocols

Read the lesson
Fill in the blankseasyProtocols

Complete the declaration so Book conforms to Describable.

struct Book Describable {
    let title: String
    func describe() -> String { title }
}
Multiple choiceeasyProtocols

Which types can conform to protocols?

Predict the outputmediumProtocols

What does this print?

protocol Greeter { func greet() -> String }
extension Greeter { func greet() -> String { "Hello" } }
struct English: Greeter {}
struct French: Greeter { func greet() -> String { "Bonjour" } }
print(English().greet(), French().greet())
Multiple choicemediumProtocols

What does adding Equatable to a struct with Equatable properties give you?

Multiple choicehardProtocols

What's the difference between some View and any View?

16Extensions

Read the lesson
Fill in the blankseasyExtensions

Complete the code so every Int gets an isPositive property.

 Int {
    var isPositive: Bool { self > 0 }
}
Predict the outputeasyExtensions

What does this print?

extension Int { var squared: Int { self * self } }
print(6.squared)
Multiple choicemediumExtensions

What can't an extension add?

Predict the outputmediumExtensions

What does this print?

extension Array where Element == Int { var total: Int { reduce(0, +) } }
print([4, 5, 6].total)
Multiple choicehardExtensions

Why add an initializer to a struct in an extension rather than in the struct itself?

17Error Handling

Read the lesson
Fill in the blankseasyError Handling

Complete the call to a throwing function.

do {
    let data =  loadFile("notes.txt")
} catch {
    print(error)
}
Multiple choiceeasyError Handling

Which protocol must a type adopt to be thrown?

Predict the outputmediumError Handling

What does this print?

enum AgeError: Error { case negative }
func check(_ age: Int) throws -> Int {
    if age < 0 { throw AgeError.negative }
    return age
}
let a = try? check(-3)
print(a ?? 0)
Multiple choicemediumError Handling

When does a defer block run?

Multiple choicehardError Handling

When is try! acceptable?

Fill in the blankseasyGenerics

Complete the declaration so the function works with any type T.

func wrap(_ value: T) -> [T] {
    [value]
}
Predict the outputeasyGenerics

What does this print?

struct Box<Value> { var value: Value }
let b = Box(value: "hi")
print(b.value.count)
Multiple choicemediumGenerics

Why does func maxOf<T>(_ a: T, _ b: T) -> T { a > b ? a : b } fail to compile?

Multiple choicemediumGenerics

What does associatedtype declare?

Multiple choicehardGenerics

What does some View as a return type mean?

19Memory & ARC

Read the lesson
Fill in the blankseasyMemory & ARC

Complete the property so it doesn't keep the delegate alive.

class TableView {
     var delegate: TableDelegate?
}
Predict the outputeasyMemory & ARC

How many times does "Freed" print?

class Item { deinit { print("Freed") } }
var x: Item? = Item()
var y = x
x = nil
Multiple choicemediumMemory & ARC

What happens to a weak reference when the object it points to is freed?

Multiple choicemediumMemory & ARC

Which types does ARC manage?

Multiple choicehardMemory & ARC

When do you need [weak self] in a closure?

20Concurrency

Read the lesson
Fill in the blankseasyConcurrency

Complete the call to the async function.

let data = try  download(url)
Multiple choiceeasyConcurrency

What does marking a function async mean?

Predict the outputmediumConcurrency

Roughly how long does this take?

async let a = wait(seconds: 2)
async let b = wait(seconds: 2)
_ = await (a, b)
Multiple choicemediumConcurrency

What does an actor guarantee?

Multiple choicehardConcurrency

Why is SwiftUI's .task modifier often better than Task { } in onAppear?

21Codable & JSON

Read the lesson
Fill in the blankseasyCodable & JSON

Complete the line that turns JSON data into a Book.

let book = try JSONDecoder().decode(, from: data)
Multiple choiceeasyCodable & JSON

Which two protocols make up Codable?

Predict the outputmediumCodable & JSON

The JSON is {"name": "Ada"}. What happens when it's decoded into struct U: Codable { let name: String; let age: Int? }?

Multiple choicemediumCodable & JSON

What does keyDecodingStrategy = .convertFromSnakeCase do?

Multiple choicehardCodable & JSON

If you write CodingKeys for a struct, what must it include?

22SwiftUI Basics

Read the lesson
Fill in the blankseasySwiftUI Basics

Complete the view so it conforms to SwiftUI's View protocol.

struct HelloView:  {
    var body: some View {
        Text("Hello")
    }
}
Multiple choiceeasySwiftUI Basics

Which stack arranges views from top to bottom?

Multiple choicemediumSwiftUI Basics

What does Spacer() do inside an HStack?

Predict the outputmediumSwiftUI Basics

Which of these gives a coloured box that includes space around the text?

Multiple choicehardSwiftUI Basics

Why does SwiftUI's body return some View rather than a named type?

23SwiftUI State

Read the lesson
Fill in the blankseasySwiftUI State

Complete the code to pass a binding to the toggle.

@State private var isOn = false
Toggle("Sound", isOn: isOn)
Multiple choiceeasySwiftUI State

Which property wrapper stores simple state owned by a single view?

Multiple choicemediumSwiftUI State

A child view needs to change a value owned by its parent. What should the child declare?

Predict the outputmediumSwiftUI State

A view has @State private var count = 0 and a button that runs count += 2 when tapped. What does Text("\(count)") show after three taps?

Multiple choicehardSwiftUI State

Where should an @Observable model shared by many screens be created?

24Lists & Navigation

Read the lesson
Fill in the blankseasyLists & Navigation

Complete the struct so it can be shown in a List without an id argument.

struct Song:  {
    let id = UUID()
    let title: String
}
Multiple choiceeasyLists & Navigation

Which container provides the navigation bar and back button?

Multiple choicemediumLists & Navigation

How is a sheet usually shown?

Predict the outputmediumLists & Navigation

cities is ["Berlin", "Lisbon", "London"] and the filter keeps names where $0.localizedCaseInsensitiveContains("ON"). How many remain?

Multiple choicehardLists & Navigation

Why does a value used with navigationDestination(for:) need to be Hashable?

Fill in the blankseasyTesting

Complete the check inside the test.

@Test func doublesNumbers() {
    (double(4) == 8)
}
Multiple choiceeasyTesting

Which attribute marks a function as a test in Swift Testing?

Multiple choicemediumTesting

What's the difference between #expect and try #require?

Predict the outputmediumTesting

How many test results does this produce?

@Test(arguments: [1, 2, 3, 4])
func isPositive(_ n: Int) { #expect(n > 0) }
Multiple choicehardTesting

Why should a view model take its API through a protocol?

26Access control

Read the lesson
Multiple choicemediumAccess control

A library should expose a struct's construction to another module. What should its author provide?

27Initialization rules

Read the lesson
Multiple choicemediumInitialization rules

A form needs to distinguish an empty code from an invalid quantity. Which construction API is useful?

28Lazy properties and wrappers

Read the lesson
Multiple choicemediumLazy properties and wrappers

A changing source must affect every read immediately. Which design most directly expresses that requirement?

29Subscripts and key paths

Read the lesson
Multiple choicemediumSubscripts and key paths

A generic function only extracts properties. Which parameter capability is sufficient?

30Type casting

Read the lesson
Multiple choicemediumType casting

A stable field has exactly three supported alternatives. Which model can make handling exhaustive?

31some and any

Read the lesson
Multiple choicemediumsome and any

Two inputs must share the same concrete conforming type. What expresses that relationship clearly?

32Collection protocols and lazy

Read the lesson
Multiple choicemediumCollection protocols and lazy

An algorithm only visits elements once and stops after enough matches. Which broad constraint fits?

33Unicode and text indices

Read the lesson
Multiple choicemediumUnicode and text indices

Which operation safely selects a visible prefix without assuming fixed-width characters?

34Native Regex

Read the lesson
Multiple choicemediumNative Regex

A token grammar requires exactly three following digits. What near miss should a search test include?

35Swift Package Manager

Read the lesson
Multiple choicemediumSwift Package Manager

An external package is declared but a target still cannot import its module. What should be checked?

36Dates and calendars

Read the lesson
Multiple choicemediumDates and calendars

What makes the payment-deadline function reproducible in tests?

37Codable file storage

Read the lesson
Multiple choicemediumCodable file storage

Two callers can update the same file from the same old snapshot. What is still required?

38URLSession HTTP contracts

Read the lesson
Multiple choicemediumURLSession HTTP contracts

Which test setup isolates response validation from live service variability?

39Async sequences and streams

Read the lesson
Multiple choicemediumAsync sequences and streams

A source emits ongoing replaceable state faster than consumption. What needs an explicit choice?

40Sendable and isolation

Read the lesson
Multiple choicemediumSendable and isolation

A UI closure needs only a product code from a mutable controller. Which capture is easier to review?

41Actor reentrancy

Read the lesson
Multiple choicemediumActor reentrancy

Which test reliably checks stale response rejection?

42Forms and validation

Read the lesson
Multiple choicemediumForms and validation

Where should reusable code-and-quantity rules live?

43SwiftData persistence

Read the lesson
Multiple choicemediumSwiftData persistence

What additional evidence is needed after an in-memory current-schema test passes?

Next steps