App Development with Swift study materials
App Development with Swift study resources

App Development with Swift practice questions

One question at a time. Build your App Development with Swift understanding.

First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Swift Language Fundamentals

Which declaration creates a name binding that cannot be reassigned after it receives its first value?

  1. let greeting = "Hello" Correct answer.
  2. final greeting = "Hello"
  3. const greeting = "Hello"
  4. var greeting = "Hello"

Explanation

The `let` keyword introduces a constant binding: once a value is bound, the same name cannot be pointed at a different value, although the internal state of a referenced object may still change. The `var` keyword is the mutable counterpart. Swift does not use `const` or `final` as variable declaration keywords.

Question 2Swift Language Fundamentals

Given `let total = 19.99`, what type does Swift infer for `total`?

  1. Float
  2. Int
  3. Double Correct answer.
  4. Decimal

Explanation

A floating-point literal with no explicit type annotation defaults to `Double`, Swift's 64-bit floating-point type. Choosing `Float` requires an explicit annotation such as `let total: Float = 19.99`. `Decimal` is never inferred from an ordinary decimal literal.

Question 3Swift Language Fundamentals

Which string literal inserts the value of the variable `count` into the resulting text?

  1. "Total: \(count)" Correct answer.
  2. "Total: %count%"
  3. "Total: ${count} units"
  4. "Total: [count]"

Explanation

String interpolation in Swift is written with a backslash immediately followed by parentheses around the expression; the expression is evaluated at runtime and converted to text. Any other bracket or percent style is treated as ordinary literal characters.

Question 4Swift Language Fundamentals

A property is declared as `var middleName: String?` and no initial value is assigned. What is its value immediately after initialization?

  1. It raises an error when first read
  2. nil Correct answer.
  3. A random leftover value
  4. An empty string

Explanation

Optional variables are automatically initialized to `nil` when no initial value is provided, so reading the property is safe. Accessing a nil optional through optional binding or optional chaining yields nil rather than crashing.

Question 5Swift Language Fundamentals

Which literal creates an array containing the integers 1, 2, and 3?

  1. {1, 2, 3}
  2. [1, 2, 3] Correct answer.
  3. (1, 2, 3)
  4. <1, 2, 3>

Explanation

Array literals use square brackets with comma-separated elements, and the element type is inferred here as `[Int]`. Parentheses build a tuple, braces delimit closures and code blocks, and angle brackets are reserved for generic syntax.

Question 6Swift Language Fundamentals

Which type annotation declares a dictionary whose keys are String and whose values are Int?

  1. [Int: String]
  2. Set<String, Int>
  3. (String, Int)
  4. [String: Int] Correct answer.

Explanation

Swift's dictionary shorthand places the key type first and the value type second, separated by a colon, so a String-to-Int mapping is `[String: Int]`. This is equivalent to `Dictionary<String, Int>`.

Question 7Swift Language Fundamentals

Which keyword begins a function declaration in Swift?

  1. function
  2. def
  3. func Correct answer.
  4. fn

Explanation

A Swift function declaration starts with `func`, followed by the name, the parameter list, an optional return type, and the body. The other keywords belong to unrelated languages.

Question 8Swift Language Fundamentals

What is the value of `shown` after `let nickname: String? = nil` followed by `let shown = nickname ?? "Guest"`?

  1. nil
  2. The text "Guest" Correct answer.
  3. The literal text "nil"
  4. An empty string

Explanation

The nil-coalescing operator `??` returns the left operand when it holds a value and the right operand when the left side is nil. Because `nickname` is nil here, `shown` receives the fallback and has the non-optional type `String`.

Question 9Swift Language Fundamentals

Which statement safely unwraps `data` and exits the current scope immediately when `data` is nil?

  1. guard data != nil else { return }
  2. if let data = data { return }
  3. guard let data = data else { return } Correct answer.
  4. let unwrapped = data! // traps when nil

Explanation

`guard let` binds the unwrapped value for the rest of the enclosing scope and requires an `else` block that exits that scope with `return`, `break`, `continue`, or `throw`. An `if let` binds the value only inside its own braces and continues afterwards.

Question 10Swift Language Fundamentals

Which statement about struct instances in Swift is accurate?

  1. Two variables can share one struct instance and see each other's mutations.
  2. A struct can inherit stored properties from a parent struct.
  3. Structs are always allocated on the heap.
  4. Assigning a struct instance to another variable copies it. Correct answer.

Explanation

Structs are value types, so assignment, argument passing, and returning from a function all produce independent copies, and mutating one copy leaves the original unchanged. Classes are Swift's reference type and are the only kind that supports inheritance.

Question 11Swift Language Fundamentals

Which type describes a closure that takes one Int argument and returns a Bool?

  1. func(Int) -> Bool
  2. Int -> Bool
  3. (Int, Bool)
  4. (Int) -> Bool Correct answer.

Explanation

Function types are written as a parenthesized parameter list, an arrow, and the return type, so a single-Int-to-Bool closure is `(Int) -> Bool`. The parentheses are required even when there is only one parameter.

Question 12Swift Language Fundamentals

Which declaration defines an enum case that carries an associated Double value?

  1. enum Shape { case circle: (Double) }
  2. enum Shape { circle(Double) }
  3. enum Shape { case circle = Double }
  4. enum Shape { case circle(Double) } Correct answer.

Explanation

Enum cases are introduced with the `case` keyword, and associated values are written in parentheses directly after the case name. The assignment form with a literal declares a raw value, which is a separate feature from associated values.

Question 13Swift Language Fundamentals

Inside a struct with stored properties `width` and `height`, which declaration creates a read-only computed property `area`?

  1. var area: Double { set { width * height } }
  2. var area: Double = { width * height }
  3. var area: Double { width * height } Correct answer.
  4. func area: Double { width * height }

Explanation

A computed property puts its logic in braces as a getter, and a getter made of a single expression can omit both `get` and `return`. Omitting the setter makes the property read-only.

Question 14Swift Language Fundamentals

`user.profile` is an optional struct with a non-optional `friends` array. What is the type of `let count = user.profile?.friends.count`?

  1. Int
  2. Int!
  3. String?
  4. Int? Correct answer.

Explanation

Optional chaining propagates optionality through the entire expression, so any member reached after `?.` yields an optional even when that member itself is non-optional. If `profile` is nil the whole chain short-circuits to nil.

Question 15Swift Language Fundamentals

Which declaration adds a new method to an existing type without subclassing it?

  1. class String: Shoutable { func shout() -> String { uppercased() } }
  2. protocol Shoutable { func shout() -> String }
  3. extension String { func shout() -> String { uppercased() } } Correct answer.
  4. override func shout() -> String { uppercased() }

Explanation

`extension` adds methods, computed properties, initializers, and protocol conformance to a type that already exists, including standard library types. Extensions cannot add stored properties or override existing members.

Question 16Swift Language Fundamentals

Which keyword in a function signature indicates that the function can propagate errors to its caller?

  1. throws Correct answer.
  2. throwing
  3. rethrow
  4. error

Explanation

A throwing function is marked with `throws` after the parameter list, and callers must handle failures with `try` inside a `do`-`catch` or propagate them further. Inside the body, an error is raised with the `throw` statement.

Question 17Swift Language Fundamentals

What does `[1, 2, 3, 4].filter { $0 % 2 == 0 }` return?

  1. [1, 2, 3, 4]
  2. [2, 4] Correct answer.
  3. [1, 3]
  4. 2

Explanation

`filter` returns a new array holding only the elements for which the closure evaluates to true, preserving the original order. The even elements in the input are 2 and 4.

Question 18Swift Language Fundamentals

In a switch statement over an Int, which case pattern matches the values 1, 2, 3, 4, and 5?

  1. case 1>..<5:
  2. case 1...5: Correct answer.
  3. case [1...5]:
  4. case 1..<5:

Explanation

The closed range operator `...` includes both endpoints, so `1...5` covers exactly the five requested values. The half-open operator `..<` excludes its upper bound.

Question 19Swift Language Fundamentals

Which declaration defines a generic function that can swap two Int, Double, or String values of the same type?

  1. func swapValues<T>(_ a: inout T, _ b: inout T) { } Correct answer.
  2. func swapValues(_ a: Any, _ b: Any) { (a, b) = (b, a) }
  3. generic func swapValues<T>(_ a: T, _ b: T) { }
  4. func swapValues<T>(a: T, b: T) { }

Explanation

A generic function declares a type parameter in angle brackets after the name, and swapping requires `inout` parameters so the caller's variables themselves are modified. The placeholder `T` is replaced with the actual argument type at each call site.

Question 20Swift Language Fundamentals

Which access level limits a declaration to its enclosing declaration and to extensions of that declaration in the same file?

  1. open
  2. internal
  3. public
  4. private Correct answer.

Explanation

`private` restricts visibility to the enclosing declaration plus extensions of that same declaration within the same file, making it the most restrictive level. `fileprivate` widens visibility to the whole file.

Question 21Swift Language Fundamentals

A class instance stores a closure property, and the closure body refers to that instance through `self`. What is the consequence?

  1. The closure captures a copy of the instance, so no cycle can form.
  2. An error is thrown the first time the closure is invoked, because self is unavailable.
  3. A retain cycle forms unless the closure captures self weakly or unowned. Correct answer.
  4. The compiler automatically converts the capture to a weak reference, preventing leaks.

Explanation

Closures capture referenced objects strongly by default, so an instance that owns a closure which in turn captures that instance creates a reference cycle and neither is deallocated. Writing `[weak self]` or `[unowned self]` in a capture list breaks the cycle.

Question 22Swift Language Fundamentals

Given `let maybeNumber: Int? = 5`, what is the type of `maybeNumber.map { String($0) }`?

  1. [String]
  2. Int?
  3. String? Correct answer.
  4. String

Explanation

`Optional.map` applies the closure to the wrapped value and re-wraps the result in an optional, so mapping an `Int?` through a String-producing closure gives `String?`. If the optional had been nil the closure would not run at all.

Question 23Swift Language Fundamentals

A `defer` block is declared at the top of a function body. When does its code run?

  1. Immediately when the declaration is reached, before the rest of the body runs
  2. Only when the function throws an error
  3. Only if the function explicitly calls it
  4. When the enclosing scope exits, including on a thrown error Correct answer.

Explanation

`defer` schedules statements to execute when the current scope is exited for any reason: a normal return, a thrown error, `break`, or `continue`. Multiple deferred blocks run in reverse order of declaration.

Question 24Swift Language Fundamentals

Why must a struct method that assigns to a stored property be marked `mutating`?

  1. Because structs cannot declare stored properties without a mutating method present
  2. Because the method needs to modify self, which is immutable by default Correct answer.
  3. Because marking it mutating is how the struct stops being a value type
  4. Because the compiler must know the method's return type before compiling the body

Explanation

Inside a struct, `self` is immutable by default, so changing a stored property requires an explicitly mutating method that takes `self` as `inout`. A mutating method cannot be called on an instance held in a `let` constant.

Question 25Swift Language Fundamentals

Given `let items: [Any] = [1, "two", 3.5, 4]`, which expression produces a `[Int]` containing only 1 and 4 without risking a runtime crash?

  1. items.filter { element in element is Int }
  2. items.flatMap { $0 as Int }
  3. items.map { $0 as! Int }
  4. items.compactMap { $0 as? Int } Correct answer.

Explanation

`compactMap` runs a closure that returns an optional and discards nil results, so `$0 as? Int` keeps only the elements that really are Ints and produces a `[Int]`. Conditional casts with `as?` never trap.

Question 26Swift Language Fundamentals

Which keyword declares a constant whose value cannot be reassigned after it is initialized?

  1. var
  2. static
  3. let Correct answer.
  4. const

Explanation

In Swift, `let` introduces a constant binding; after the initial assignment, the value cannot be changed. `var` introduces a mutable variable. The other keywords do not declare an immutable local constant.

Question 27Swift Language Fundamentals

What is the default value of an optional stored property that has no explicit initializer?

  1. It must always be assigned in an initializer
  2. nil Correct answer.
  3. An empty string
  4. 0

Explanation

An optional stored property without an explicit initializer is automatically set to nil. Swift does not give optionals a zero or empty-string default. An initializer assignment is not required solely because the property is optional.

Question 28Swift Language Fundamentals

Which collection type stores unique values and does not preserve insertion order?

  1. Dictionary
  2. Set Correct answer.
  3. Tuple
  4. Array

Explanation

A Set stores unique elements and is unordered, so it does not preserve insertion order. An Array preserves order and permits duplicates. A Dictionary stores key-value pairs, and a tuple is a fixed group of values rather than a uniqueness-enforcing collection.

Question 29Swift Language Fundamentals

Which syntax inserts the value of `name` into a string literal?

  1. \(name) Correct answer.
  2. {{name}}
  3. %@
  4. $(name)

Explanation

Swift string interpolation uses a backslash followed by parentheses: `\(name)`. The expression inside the parentheses is evaluated and inserted into the string. The other forms are not Swift interpolation syntax.

Question 30Swift Language Fundamentals

What sequence of values does `stride(from: 0, to: 10, by: 3)` produce?

  1. 3, 6, 9
  2. 0, 3, 6, 9, 12
  3. 0, 3, 6, 9 Correct answer.
  4. 0, 3, 6

Explanation

`stride(from:to:by:)` starts at the lower value and stops before reaching the upper bound. Adding 3 repeatedly yields 0, 3, 6, and 9. The value 12 is excluded because the upper bound 10 is exclusive.

Question 31Swift Language Fundamentals

When does a `didSet` observer on a stored property run?

  1. Only when the property is read
  2. After the new value is stored, but not during initialization Correct answer.
  3. Only when the property is declared with `lazy`
  4. Before the new value is stored

Explanation

`didSet` runs immediately after a new value has been stored. Property observers are not called while the property is being initialized. `willSet` runs before storage, and reading a property does not trigger either observer.

Question 32Swift Language Fundamentals

What must be true of a `switch` statement over a non-optional enum in Swift?

  1. It must use `@unknown default` in every branch
  2. It must handle every case or include a `default` clause Correct answer.
  3. It must include a `default` clause even when all cases are covered
  4. It may omit cases that are unlikely to occur

Explanation

Swift switches must be exhaustive, so every possible value of the switched type must be matched by a case or by a default clause. A default clause is not required when all cases are explicitly covered. `@unknown default` is relevant only for non-frozen enums declared outside the current module.

Question 33Swift Language Fundamentals

What does marking a class method as `final` accomplish?

  1. It prevents the method from being called
  2. It prevents the method from being marked private
  3. It prevents subclasses from overriding the method Correct answer.
  4. It prevents the method from returning a value

Explanation

The `final` modifier stops subclasses from overriding the method. It does not change whether the method is callable, its access level, or its return type. Marking a method final can also help the compiler optimize dispatch.

Question 34Swift Language Fundamentals

Which statement is accurate about a stored property declared with `lazy var`?

  1. It must be declared inside a struct
  2. It cannot refer to `self`
  3. It is recomputed on every access
  4. It is initialized only when first accessed Correct answer.

Explanation

A lazy stored property is initialized the first time it is accessed, rather than when the containing instance is created. The computed value is stored and reused, so it is not recomputed on each access. Lazy properties can refer to `self` because initialization happens after the instance exists.

Question 35Swift Language Fundamentals

Which protocol must a type conform to before it can be used as a Dictionary key?

  1. Comparable
  2. Equatable
  3. Hashable Correct answer.
  4. Codable

Explanation

Dictionary keys must conform to `Hashable`, which supplies the hash value used for efficient lookup. `Hashable` inherits from `Equatable`, but `Equatable` alone is not enough. `Comparable` and `Codable` are unrelated to the dictionary key requirement.

Question 36Swift Language Fundamentals

What does the expression `Int("42")` return?

  1. A `String` equal to "42"
  2. A plain `Int` equal to 42
  3. An `Int?` containing 42 Correct answer.
  4. A runtime error every time

Explanation

`Int("42")` uses a failable initializer and returns `Int?`. Valid numeric text produces an optional containing the integer, while invalid text produces nil. It does not return a plain `Int` or throw an error.

Question 37Swift Language Fundamentals

What does the `@escaping` attribute indicate about a closure parameter?

  1. The closure runs before the function returns
  2. The closure may outlive the function call and be stored Correct answer.
  3. The closure must be optional
  4. The closure cannot capture values

Explanation

`@escaping` tells the compiler that a closure argument may be stored and called after the function returns. Non-escaping closures are guaranteed to finish before the function returns. The attribute does not restrict captures or make the parameter optional.

Question 38Swift Language Fundamentals

A throwing function returns `Int`. In Swift 5 and later, what is the type of `try? makeNumber()`?

  1. Void
  2. Int??
  3. Int? Correct answer.
  4. Int

Explanation

In Swift 5 and later, `try?` does not add an extra level of optionality. Calling a throwing function that returns `Int` with `try?` produces an `Int?`, where nil represents a thrown error. Earlier Swift versions produced `Int??`, but current Swift flattens the result.

Question 39Swift Language Fundamentals

Which condition allows Swift to synthesize `Equatable` conformance for a struct?

  1. The struct is marked `final`
  2. Every stored property's type conforms to `Equatable` Correct answer.
  3. The struct declares no methods
  4. All stored properties are declared with `var`

Explanation

Swift can synthesize `Equatable` for a struct when all of its stored properties have types that conform to `Equatable`. The presence of methods, the `final` modifier, or `let` versus `var` does not affect synthesis. If any stored property is not Equatable, conformance must be implemented manually.

Question 40Swift Language Fundamentals

What happens when a value is passed to an `inout` parameter?

  1. The argument is passed by reference without any copying
  2. The argument becomes immutable inside the function
  3. The argument is copied in, modified, and copied back out Correct answer.
  4. Only class instances can be passed to an `inout` parameter

Explanation

An `inout` parameter uses copy-in copy-out semantics: the argument's value is copied into the function, modified, and written back to the caller's storage when the function returns. It is not a simple by-reference alias, and the argument must be a mutable lvalue. Classes can be passed inout, but the parameter is not restricted to classes.

Question 41Control Flow, Functions, and Closures

When `score` is 59, what is assigned to `label` by `let label = score >= 60 ? "Pass" : "Fail"`?

  1. "Fail" Correct answer.
  2. "Pass"
  3. A compile-time error occurs because 59 is not a Boolean.
  4. nil

Explanation

The ternary operator evaluates the condition. When the condition is false, it returns the value after the colon, so "Fail" is assigned. "Pass" is returned only when `score >= 60` is true.

Question 42Control Flow, Functions, and Closures

A switch statement lists every case of an enum and has no default case. What is true?

  1. It fails to compile because every switch must include `default`.
  2. It compiles only if the enum conforms to `CaseIterable`.
  3. It compiles only if each case body ends with `fallthrough`.
  4. It compiles because the switch is exhaustive. Correct answer.

Explanation

Swift requires a switch over an enum to handle every case unless a default is present. Listing all cases makes the switch exhaustive, so no default is needed. Case bodies do not need `fallthrough`, and `CaseIterable` is unrelated to switch exhaustiveness.

Question 43Control Flow, Functions, and Closures

What sequence does `stride(from: 0, to: 10, by: 3)` produce?

  1. 0, 3, 6, 9, 10
  2. 0, 3, 6, 9, 12
  3. 0, 3, 6, 9 Correct answer.
  4. 0, 3, 6

Explanation

`stride(from:to:by:)` starts at 0 and stops before reaching 10. Adding 3 repeatedly gives 0, 3, 6, and 9; the next value, 12, is beyond the upper bound. The upper bound itself is excluded when using `to:`.

Question 44Control Flow, Functions, and Closures

Which statement about a `repeat-while` loop is true?

  1. It executes its body at least once before checking the condition. Correct answer.
  2. It is not allowed when the condition uses a Boolean variable.
  3. It checks the condition before the first iteration.
  4. It may execute its body zero times if the condition is false initially.

Explanation

A `repeat-while` loop runs its body first and evaluates the condition afterward. Therefore the body always executes at least once. A `while` loop is the form that checks the condition before the first iteration.

Question 45Control Flow, Functions, and Closures

Given `func greet(name: String = "Guest") -> String { return "Hello, \(name)" }`, what does `greet()` return?

  1. "Hello, name"
  2. A compile-time error, because `name` has no argument.
  3. "Hello, Guest" Correct answer.
  4. "Hello, " with no name.

Explanation

A default parameter value is used when the caller omits that argument. Calling `greet()` supplies no name, so `name` becomes `"Guest"`. The return value is therefore `"Hello, Guest"`.

Question 46Control Flow, Functions, and Closures

Given `func total(_ values: Int...) -> Int { return values.reduce(0, +) }`, what is `total(1, 2, 3)`?

  1. 6 Correct answer.
  2. A compile-time error, because a variadic parameter cannot be passed three arguments.
  3. [1, 2, 3]
  4. 3

Explanation

A variadic parameter accepts zero or more arguments of the stated type and collects them into an array. Here `values` is `[1, 2, 3]`, and reducing with `+` sums it to 6. Passing several arguments to a variadic parameter is exactly the intended use.

Question 47Control Flow, Functions, and Closures

What is the value of `[1, 2, 3].map { $0 * 2 }`?

  1. [1, 4, 9]
  2. [2, 4, 6] Correct answer.
  3. [1, 2, 3]
  4. A compile-time error, because `$0` is not declared.

Explanation

Inside a closure, `$0` is shorthand for the first argument. The closure multiplies each element by 2, and `map` returns a new array with the transformed values. The result is therefore `[2, 4, 6]`.

Question 48Control Flow, Functions, and Closures

Which is required at the end of a `guard` statement's `else` block?

  1. A `default` case.
  2. A `fallthrough` statement.
  3. An assignment to the guarded variable.
  4. A statement that exits the current scope, such as `return`, `break`, `continue`, or `throw`. Correct answer.

Explanation

The `else` block of a `guard` statement must transfer control out of the current scope. Valid exits include `return`, `break`, `continue`, `throw`, or a call to a function that never returns. Execution cannot simply continue past the `else` block.

Question 49Control Flow, Functions, and Closures

With `value` equal to 1, what does this code print? ``` switch value { case 1: print("A") fallthrough case 2: print("B") default: break } ```

  1. A compile-time error occurs because `fallthrough` cannot follow a nonempty case.
  2. B only
  3. A only
  4. A then B Correct answer.

Explanation

`fallthrough` transfers execution into the next case body without testing that case's pattern. Since the first case prints "A" and then falls through, the second case prints "B". The combined output is "A" followed by "B".

Question 50Control Flow, Functions, and Closures

Which value is matched by the switch case pattern `13...19`?

  1. 19 Correct answer.
  2. 12
  3. 20
  4. 21

Explanation

The `...` operator creates a closed range, which includes both endpoints. Therefore `13...19` matches every integer from 13 through 19. Among the choices, only 19 lies within that range.