Swift quiz – 40 questions with answers
Try it interactively
With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.
Beginner (14 questions)
How do you declare a constant in Swift?
- const x = 5
- let x = 5
- val x = 5
- final x = 5
Show answer
Correct: let x = 5
let creates an immutable constant, var a mutable variable.
What type does let x = 3.14 have?
- Float
- Double
- Decimal
- CGFloat
Show answer
Correct: Double
Floating-point literals are inferred as Double by default.
What does this code print?
let a = 7
let b = 2
print(a / b)- 3.5
- 3
- 4
- Compiler error
Show answer
Correct: 3
Both operands are Int, so this is integer division: 3. For 3.5 you would need Double(a) / Double(b).
Does this compile?
let x = 5
x = 6- Yes, x is 6 afterwards
- No: a constant (let) cannot be changed
- Yes, but with a warning
- No: x has no type
Show answer
Correct: No: a constant (let) cannot be changed
Constants are immutable after initialization. With var it would be allowed.
What does this code print?
let s: String? = "Hi"
print(s)- Hi
- Optional("Hi")
- some(Hi)
- Compiler error
Show answer
Correct: Optional("Hi")
print outputs the optional itself, that is Optional("Hi"). To unwrap it you need if let, ??, or !.
What does the ?? operator do?
- Forces unwrapping of an optional
- Returns the optional's value or a default value if it is nil
- Compares two optionals
- Checks whether a value is an Int
Show answer
Correct: Returns the optional's value or a default value if it is nil
Nil-coalescing: a ?? b yields a if it has a value, otherwise b.
What happens here at runtime?
let zahlen = [1, 2, 3]
let i = 3
print(zahlen[i])- Output: nil
- Output: 0
- Runtime error: Index out of range (crash)
- Compiler error
Show answer
Correct: Runtime error: Index out of range (crash)
An index out of bounds causes a crash with arrays; Swift does not return nil here. Safe: zahlen.indices.contains(i) or first/last.
How do you insert the value of name into a string?
- "Hello ${name}"
- "Hello \(name)"
- "Hello {name}"
- "Hello " + $name
Show answer
Correct: "Hello \(name)"
You write string interpolation as \(expression).
What does this code print?
for i in 0..<3 {
print(i, terminator: " ")
}- 0 1 2
- 0 1 2 3
- 1 2 3
- Compiler error
Show answer
Correct: 0 1 2
0..<3 is half-open: 0, 1, 2. terminator: " " appends a space instead of a line break.
Which values does the range 1...3 have?
- 1, 2
- 1, 2, 3
- 0, 1, 2
- 2, 3
Show answer
Correct: 1, 2, 3
The closed range 1...3 includes both bounds.
What applies to switch in Swift?
- It must be exhaustive and does not fall through automatically
- Every case needs a
break - It only works with Int values
- It falls through to the next case by default
Show answer
Correct: It must be exhaustive and does not fall through automatically
All possible values must be covered (with default if needed), and after a case the switch ends; fallthrough only exists explicitly.
What does this code print?
var a = [1, 2]
var b = a
b.append(3)
print(a)- [1, 2]
- [1, 2, 3]
- [3]
- Compiler error
Show answer
Correct: [1, 2]
Arrays are value types: b = a creates a (logical) copy. Changes to b do not affect a.
How do you correctly call func verdopple(_ x: Int, mal faktor: Int) -> Int?
- verdopple(x: 3, faktor: 2)
- verdopple(3, mal: 2)
- verdopple(3, faktor: 2)
- verdopple(_: 3, mal: 2)
Show answer
Correct: verdopple(3, mal: 2)
Because of _, the first parameter has no label; the second is called with its argument label mal:.
What does this code print?
let d = ["a": 1]
print(d["b"])- nil
- 0
- Optional(0)
- Runtime error
Show answer
Correct: nil
Accessing a dictionary returns an optional; if the key is missing, it is nil.
Intermediate (14 questions)
What is the core difference between struct and class?
- Structs are reference types, classes are value types
- Structs are value types (copied), classes are reference types (shared)
- Only classes can have methods
- Structs are always immutable
Show answer
Correct: Structs are value types (copied), classes are reference types (shared)
Value types are copied on assignment; reference types share one instance. Only classes also support inheritance and deinit.
What does this code print?
struct P { var x = 1 }
var a = P()
var b = a
b.x = 99
print(a.x, b.x)- 1 99
- 99 99
- 1 1
- Compiler error
Show answer
Correct: 1 99
A struct is a value type: b is its own copy. With a class the output would be 99 99.
What does this code print?
class Z {
var wert = 0
func increment() { wert += 1 }
}
let z1 = Z()
let z2 = z1
z2.increment()
print(z1.wert)- 0
- 1
- 2
- Compiler error because z2 is a let
Show answer
Correct: 1
Both constants point to the same instance; let only protects the reference, not the properties of the object.
When must a struct method be mutating?
- When it returns a value
- When it modifies properties of the struct instance
- When it is static
- Always
Show answer
Correct: When it modifies properties of the struct instance
Because structs are value types, a modifying method must be marked mutating (and can only be called on var instances).
Does this compile?
struct P { var x: Int }
let p = P(x: 1)
p.x = 5- Yes
- No: p is a constant, and for structs p.x is then immutable too
- Only with mutating
- Yes, but with a warning
Show answer
Correct: No: p is a constant, and for structs p.x is then immutable too
For value types, let applies to the whole value. With a class the assignment would be allowed.
What are associated values in enums?
- Raw values such as Int or String that are permanently assigned to each case
- Data that each case can additionally store, e.g.
case kreis(radius: Double) - Static constants of the enum
- A kind of protocol
Show answer
Correct: Data that each case can additionally store, e.g. case kreis(radius: Double)
Associated values let each case carry its own data; in a switch you read them out via a pattern.
What does this code print?
enum Wochentag: Int {
case montag = 1, dienstag, mittwoch
}
print(Wochentag.mittwoch.rawValue)- 2
- 3
- mittwoch
- Compiler error
Show answer
Correct: 3
With Int raw values, Swift counts up from the last specified value: montag = 1, dienstag = 2, mittwoch = 3.
How do you give a protocol default behavior?
- Through a base class
- Through an
extensionof the protocol with implementations - With the keyword
default - It is not possible
Show answer
Correct: Through an extension of the protocol with implementations
Protocol extensions provide default implementations. Types that conform to the protocol inherit them automatically and can override them if the method is part of the protocol.
What does [any Tier] mean?
- An array of arbitrary values
- An array of values of different types that all conform to the protocol Tier
- An array that contains only classes
- An array of optional animals
Show answer
Correct: An array of values of different types that all conform to the protocol Tier
any Protocol is an existential: it can hold any concrete type that conforms to the protocol (with a dynamic call).
What does this code print?
let z = [1, 2, 3, 4]
print(z.filter { $0 % 2 == 0 }.map { $0 * 10 })- [20, 40]
- [10, 30]
- [2, 4]
- [10, 20, 30, 40]
Show answer
Correct: [20, 40]
filter keeps 2 and 4, map multiplies by 10: [20, 40].
What does this code print?
func macher() -> () -> Int {
var n = 0
return { n += 1; return n }
}
let c = macher()
_ = c()
print(c())- 1
- 2
- 0
- Compiler error
Show answer
Correct: 2
The closure captures n and keeps it between calls. The first call returns 1, the second 2.
What does try? f() return if f throws an error?
- The error as a value
- nil
- A crash
- The default value of the return type
Show answer
Correct: nil
try? converts the result into an optional: on an error it is nil. try! would crash.
What must be in the else block of a guard?
- An expression that yields true
- A statement that leaves the current scope (return, throw, break, continue)
- Nothing, it is optional
- A
defer
Show answer
Correct: A statement that leaves the current scope (return, throw, break, continue)
guard enforces that the else branch leaves the scope, so the unwrapped values are safely available afterwards.
What does this code print?
enum Form {
case kreis(Double)
case quadrat(Double)
}
let f = Form.quadrat(3)
switch f {
case .kreis(let r): print(r * 2)
case .quadrat(let s): print(s * s)
}- 9.0
- 9
- 6.0
- Compiler error
Show answer
Correct: 9.0
The associated value is a Double (3.0); s * s gives 9.0, and Swift prints a Double with a decimal place.
Advanced (12 questions)
When does ARC free a class object?
- After a fixed time interval
- When no strong reference points to it anymore
- When the garbage collector runs
- When
free()is called
Show answer
Correct: When no strong reference points to it anymore
ARC counts strong references. When the counter drops to 0, the object is freed immediately (deinit runs).
What does weak var besitzer: Person? do?
- The reference does not increase the reference count and automatically becomes nil when the object is freed
- The reference is constant
- The reference is thread-safe
- The object is freed immediately
Show answer
Correct: The reference does not increase the reference count and automatically becomes nil when the object is freed
weak does not keep the object alive and sets itself to nil when it is freed, which is why the variable must be an optional. This avoids retain cycles.
What does this code print?
class A { var b: B?; deinit { print("A gone") } }
class B { var a: A?; deinit { print("B gone") } }
var x: A? = A()
var y: B? = B()
x?.b = y
y?.a = x
x = nil
y = nil- A gone, B gone
- Nothing: a retain cycle keeps both alive
- B gone, A gone
- Compiler error
Show answer
Correct: Nothing: a retain cycle keeps both alive
A holds B strongly and B holds A strongly; even after x = nil and y = nil each count stays at 1. Neither object is ever freed. Solution: make one side weak.
What does [weak self] stand for in { [weak self] in ... }?
- The closure may only be called once
- The closure holds self only weakly, to avoid a retain cycle
- The closure runs on the main thread
- self is copied
Show answer
Correct: The closure holds self only weakly, to avoid a retain cycle
The capture list determines how values are captured. weak self prevents closure and object from holding each other; self is then an optional.
What happens at await in an async function?
- The whole thread blocks until the result is available
- The function is suspended; the thread can do other work
- The code runs in a new process
- An error is thrown
Show answer
Correct: The function is suspended; the thread can do other work
await marks a suspension point: the function pauses without blocking the thread and is resumed later.
What does this code print?
func f(_ n: Int) async -> Int { n * 2 }
let a = await f(1)
async let b = f(2)
print(a, await b)- 2 4
- 1 2
- 2 2
- Compiler error: async let is invalid
Show answer
Correct: 2 4
a is 1 * 2 = 2, b is 2 * 2 = 4 (started in parallel, collected with await b).
What is an actor for?
- For UI elements
- It protects mutable state from data races by allowing only one access at a time
- It replaces protocols
- It speeds up loops
Show answer
Correct: It protects mutable state from data races by allowing only one access at a time
Actors serialize access to their state. From the outside, their methods are async and are called with await.
What does @MainActor do?
- The code is executed in parallel on several cores
- The code is guaranteed to run on the main thread (important for UI)
- The code is compiled more slowly but more safely
- The type becomes a class
Show answer
Correct: The code is guaranteed to run on the main thread (important for UI)
@MainActor isolates code to the main actor, the main thread. UI updates must happen there.
What triggers a recomputation of body in SwiftUI when zaehler changes?
- A manual call to reload()
- The declaration
@State private var zaehler = 0 - A timer
- The call
body.update()
Show answer
Correct: The declaration @State private var zaehler = 0
@State (or @Observable, @Binding …) makes SwiftUI aware of changes. Views are a function of state.
Does this compile?
func laden() async -> Int { 42 }
func start() {
let x = laden()
print(x)
}- Yes, prints 42
- No: missing await, and start() is not an async function
- No: laden needs throws
- Yes, but with a warning
Show answer
Correct: No: missing await, and start() is not an async function
An async function must be called with await, which is only possible from an async context (or inside Task { ... }).
What does $name mean for @State var name = ""?
- A copy of the value
- A binding, a two-way connection to the state
- A pointer to the address
- An optional
Show answer
Correct: A binding, a two-way connection to the state
The dollar sign yields the projectedValue of the property wrapper, which for @State is a Binding<String>, e.g. for TextField("Name", text: $name).
What does extension Array where Element: Numeric { ... } do?
- The extension applies to all arrays
- The extension is only available for arrays whose elements are numeric types
- It removes all non-numeric elements
- It creates a new array protocol
Show answer
Correct: The extension is only available for arrays whose elements are numeric types
With where you restrict an extension to types that satisfy a condition, here [Int], [Double], etc., but not [String].