SwSwift

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?

  1. const x = 5
  2. let x = 5
  3. val x = 5
  4. 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?

  1. Float
  2. Double
  3. Decimal
  4. 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)
  1. 3.5
  2. 3
  3. 4
  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
  1. Yes, x is 6 afterwards
  2. No: a constant (let) cannot be changed
  3. Yes, but with a warning
  4. 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)
  1. Hi
  2. Optional("Hi")
  3. some(Hi)
  4. 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?

  1. Forces unwrapping of an optional
  2. Returns the optional's value or a default value if it is nil
  3. Compares two optionals
  4. 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])
  1. Output: nil
  2. Output: 0
  3. Runtime error: Index out of range (crash)
  4. 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?

  1. "Hello ${name}"
  2. "Hello \(name)"
  3. "Hello {name}"
  4. "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: " ")
}
  1. 0 1 2
  2. 0 1 2 3
  3. 1 2 3
  4. 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. 1, 2
  2. 1, 2, 3
  3. 0, 1, 2
  4. 2, 3
Show answer

Correct: 1, 2, 3

The closed range 1...3 includes both bounds.

What applies to switch in Swift?

  1. It must be exhaustive and does not fall through automatically
  2. Every case needs a break
  3. It only works with Int values
  4. 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. [1, 2]
  2. [1, 2, 3]
  3. [3]
  4. 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?

  1. verdopple(x: 3, faktor: 2)
  2. verdopple(3, mal: 2)
  3. verdopple(3, faktor: 2)
  4. 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"])
  1. nil
  2. 0
  3. Optional(0)
  4. 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?

  1. Structs are reference types, classes are value types
  2. Structs are value types (copied), classes are reference types (shared)
  3. Only classes can have methods
  4. 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. 1 99
  2. 99 99
  3. 1 1
  4. 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)
  1. 0
  2. 1
  3. 2
  4. 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?

  1. When it returns a value
  2. When it modifies properties of the struct instance
  3. When it is static
  4. 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
  1. Yes
  2. No: p is a constant, and for structs p.x is then immutable too
  3. Only with mutating
  4. 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?

  1. Raw values such as Int or String that are permanently assigned to each case
  2. Data that each case can additionally store, e.g. case kreis(radius: Double)
  3. Static constants of the enum
  4. 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)
  1. 2
  2. 3
  3. mittwoch
  4. 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?

  1. Through a base class
  2. Through an extension of the protocol with implementations
  3. With the keyword default
  4. 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?

  1. An array of arbitrary values
  2. An array of values of different types that all conform to the protocol Tier
  3. An array that contains only classes
  4. 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 })
  1. [20, 40]
  2. [10, 30]
  3. [2, 4]
  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. 1
  2. 2
  3. 0
  4. 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?

  1. The error as a value
  2. nil
  3. A crash
  4. 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?

  1. An expression that yields true
  2. A statement that leaves the current scope (return, throw, break, continue)
  3. Nothing, it is optional
  4. 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)
}
  1. 9.0
  2. 9
  3. 6.0
  4. 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?

  1. After a fixed time interval
  2. When no strong reference points to it anymore
  3. When the garbage collector runs
  4. 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?

  1. The reference does not increase the reference count and automatically becomes nil when the object is freed
  2. The reference is constant
  3. The reference is thread-safe
  4. 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
  1. A gone, B gone
  2. Nothing: a retain cycle keeps both alive
  3. B gone, A gone
  4. 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 ... }?

  1. The closure may only be called once
  2. The closure holds self only weakly, to avoid a retain cycle
  3. The closure runs on the main thread
  4. 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?

  1. The whole thread blocks until the result is available
  2. The function is suspended; the thread can do other work
  3. The code runs in a new process
  4. 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)
  1. 2 4
  2. 1 2
  3. 2 2
  4. 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?

  1. For UI elements
  2. It protects mutable state from data races by allowing only one access at a time
  3. It replaces protocols
  4. 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?

  1. The code is executed in parallel on several cores
  2. The code is guaranteed to run on the main thread (important for UI)
  3. The code is compiled more slowly but more safely
  4. 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?

  1. A manual call to reload()
  2. The declaration @State private var zaehler = 0
  3. A timer
  4. 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)
}
  1. Yes, prints 42
  2. No: missing await, and start() is not an async function
  3. No: laden needs throws
  4. 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 = ""?

  1. A copy of the value
  2. A binding, a two-way connection to the state
  3. A pointer to the address
  4. 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?

  1. The extension applies to all arrays
  2. The extension is only available for arrays whose elements are numeric types
  3. It removes all non-numeric elements
  4. 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].