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.
Topic All topics Introduction Variables & Constants Numbers & Operators Strings Optionals if & switch Loops Functions Arrays Dictionaries & Sets Closures Structs Classes Enums Protocols Extensions Error Handling Generics Memory & ARC Concurrency Codable & JSON SwiftUI Basics SwiftUI State Lists & Navigation Testing Access control Initialization rules Lazy properties and wrappers Subscripts and key paths Type casting some and any Collection protocols and lazy Unicode and text indices Native Regex Swift Package Manager Dates and calendars Codable file storage URLSession HTTP contracts Async sequences and streams Sendable and isolation Actor reentrancy Forms and validation SwiftData persistence
All types Fill in the blanks Predict the output Multiple choice
Any level Easy Medium Hard
Score 0 / 143
Complete the line so it shows Hi in the console.
( "Hi" )
print shows a value in the console.
Check answer Show solution
print ( "A" , "B" , "C" , separator: "" )
A ABC B A B C C A,B,C D A-B-C
An empty separator joins the values with nothing between them.
Show answer
print ( "2 + 2" )
print ( 2 + 2 )
A 4 and 4 B 2 + 2 twice C 2 + 2, then 4 D An error
Quoted text is printed as written; the sum is calculated.
Show answer
Which file extension do Swift source files use?
A .sw B .swift C .sft D .playground only
Playgrounds are a special format, but source files end in .swift.
Show answer
Which tool is used to build and publish iPhone apps?
A Android Studio B Notepad C Swift Playgrounds only D Xcode
Xcode builds, tests and submits apps to the App Store.
Show answer
Complete the declaration so the value can never change.
maxPlayers = 4
let creates a constant.
Check answer Show solution
What type does Swift infer for let x = 4.0?
A Int B Float C Double D String
Decimal literals are Doubles by default.
Show answer
var a = 5
let b = a
a = 9
print ( b)
A 9 B 5 C 14 D An error
b got the value 5 when it was created.
Show answer
Which line correctly multiplies an Int count by 2.5?
A count * 2.5 B (Double) count * 2.5 C count.toDouble() * 2.5 D Double(count) * 2.5
Swift needs an explicit conversion.
Show answer
What type does Int("abc") produce?
A Int, with the value 0 B String C Int? (an optional), here containing nil D It crashes
Conversions from text can fail, so they return optionals.
Show answer
Complete the code so it shows the remainder of 17 divided by 5.
print ( 17 5 )
% gives the remainder: 2.
Check answer Show solution
What does print(9 / 2) show?
A 4.5 B 4 C 5 D 4.0
Both are Ints, so the decimals are dropped.
Show answer
var x = 10
x -= 3
x *= 2
print ( x)
A 17 B 20 C 7 D 14
10 minus 3 is 7, and 7 times 2 is 14.
Show answer
How do you add one to a variable in Swift?
A count++ B ++count C count += 1 D count.increment()
++ was removed from Swift.
Show answer
What happens if an Int calculation goes past Int's maximum value?
A It wraps to a negative number B The program stops with an overflow error C It becomes a Double D It stays at the maximum
Swift traps overflow; &+ wraps if you really want that.
Show answer
Complete the interpolation so it prints "Hello, Ada".
let name = "Ada"
print ( "Hello, ")
\(name) inserts the value of name.
Check answer Show solution
What does print("Swift".count) show?
A 4 B 6 C Swift D 5
S-w-i-f-t is five characters.
Show answer
print ( "banana" . prefix ( 3 ) , "banana" . suffix ( 2 ) )
A ban na B ban ana C nan ba D b na
The first three characters, then the last two.
Show answer
Why can't you write text[2] to read a character in Swift?
A Strings are immutable B Indexes start at 1 C Characters can take different amounts of storage, so Swift doesn't allow integer indexes D Only arrays have characters
Use first, prefix, dropFirst or String.Index instead.
Show answer
let words = "a b c" . split ( separator: " " )
print ( words. joined ( separator: "" ) )
A a b c B abc C ["a", "b", "c"] D a,b,c
split removes the spaces and joining with "" puts the letters together.
Show answer
Complete the declaration so middleName can be nil.
var middleName: String = nil
The question mark makes the type optional.
Check answer Show solution
let city: String ? = nil
print ( city ? ? "Unknown" )
A Unknown B nil C Optional(nil) D An error
?? uses the default when the optional is nil.
Show answer
let word: String ? = "swift"
print ( word? . uppercased ( ) . count ? ? 0 )
A SWIFT B 0 C 5 D Optional(5)
word has a value, so the chain gives 5 and ?? isn't needed.
Show answer
What must the else block of a guard let do?
A Nothing special B Print an error C Set the value to nil D Leave the current scope, for example with return, break or throw
After guard, the unwrapped value is available for the rest of the scope.
Show answer
When is force unwrapping with ! reasonable?
A Whenever it makes code shorter B Only when nil is impossible and a crash would reveal a programming mistake C For user input D For network responses
In everyday code, prefer if let, guard let or ??.
Show answer
Complete the ternary so label is "Even" or "Odd".
let label = n % 2 == 0 "Even" : "Odd"
condition ? valueIfTrue : valueIfFalse.
Check answer Show solution
let x = 7
switch x {
case 1 , 3 , 5 , 7 , 9 : print ( "odd" )
default : print ( "even" )
}
A even B odd, then even C Nothing D odd
7 matches the first case, and switch never falls through.
Show answer
let t = 18
if t > 25 { print ( "hot" ) } else if t > 15 { print ( "mild" ) } else if t > 5 { print ( "cool" ) }
A hot B mild C mild and cool D cool
Only the first true branch runs.
Show answer
Which case matches every number from 10 up to, but not including, 20?
A case 10...20: B case 10, 20: C case 10..<20: D case 10-20:
..< excludes the upper bound.
Show answer
What does case let (x, y) where x > y: do?
A Assigns new values to x and y B Compares two variables declared earlier C Binds the tuple's parts to x and y and matches only when x is greater than y D It's not valid Swift
let binds values; where adds a condition.
Show answer
Fill in the blankseasy Loops Complete the loop so it runs for 0, 1, 2 and 3.
for i in 0 4 { print ( i) }
..< creates a half-open range that stops before 4.
Check answer Show solution
Predict the outputeasy Loops How many times does for _ in 1...3 { } run?
A 2 B 4 C 3 D 0
The closed range includes 1, 2 and 3.
Show answer
Predict the outputmedium Loops
for x in stride ( from: 1 , to: 10 , by: 3 ) { print ( x, terminator: " " ) }
A 1 4 7 10 B 1 4 7 C 3 6 9 D 1 3 6 9
to: excludes the end, so 10 isn't included.
Show answer
Multiple choicemedium Loops Which loop always runs its body at least once?
A for-in B repeat-while C while D stride
repeat-while checks its condition after the body.
Show answer
Predict the outputhard Loops
var total = 0
for n in 1 . . . 6 where n != 4 {
total += n
}
print ( total)
A 21 B 6 C 10 D 17
1 + 2 + 3 + 5 + 6 = 17.
Show answer
Complete the declaration so the function can be called as square(4).
func square ( n: Int ) -> Int { n * n }
_ removes the argument label.
Check answer Show solution
func greet ( _ name: String = "friend" ) -> String { "Hi, \(name)" }
print ( greet ( ) )
A Hi, B Hi, name C Hi, friend D An error
The default value is used when no argument is given.
Show answer
func total ( _ xs: Int . . . ) -> Int { xs. reduce ( 0 , + ) }
print ( total ( 1 , 2 , 3 , 4 ) )
A 4 B 1234 C [1, 2, 3, 4] D 10
The variadic parameter collects all four numbers, which are added up.
Show answer
How do you call func move(from start: String, to end: String)?
A move(start: "A", end: "B") B move("A", "B") C move(from: "A", to: "B") D move(from start: "A", to end: "B")
Callers use the argument labels.
Show answer
What does an inout parameter allow?
A The function changes the caller's variable, which is passed with & B Returning several values C Optional parameters D Any number of arguments
Changes are written back when the function returns.
Show answer
Complete the code so "eggs" is added to the end of the basket.
var basket = [ "bread" ]
basket. ( "eggs" )
append adds an item to the end of a var array.
Check answer Show solution
let xs = [ "a" , "b" , "c" , "d" ]
print ( xs[ 2 ] )
A c B b C d D An error
Indexes start at 0, so index 2 is the third item.
Show answer
Predict the outputmedium Arrays
var xs = [ 5 , 3 , 8 ]
xs. insert ( 1 , at: 0 )
xs. remove ( at: 2 )
print ( xs)
A [5, 3, 8, 1] B [1, 5, 8] C [1, 3, 8] D [1, 5, 3]
After inserting at 0 the array is [1, 5, 3, 8]; removing index 2 removes the 3.
Show answer
What's the difference between sort() and sorted()?
A sort is faster B sorted only works on numbers C sort changes a var array in place; sorted returns a new array D There's none
sorted() works on let arrays too.
Show answer
var a = [ 1 , 2 ]
var b = a
b. append ( 3 )
print ( a. count , b. count )
A 3 3 B 2 2 C An error D 2 3
Arrays are value types, so b is an independent copy.
Show answer
Complete the code so it reads the count for "cat", or 0 if it isn't there.
let n = counts[ "cat" , : 0 ]
The default subscript returns a fallback value for missing keys.
Check answer Show solution
let d = [ "a" : 1 , "b" : 2 ]
print ( d[ "c" ] ? ? - 1 )
A -1 B 0 C nil D A crash
The key is missing, so ?? supplies -1.
Show answer
var s: Set = [ 1 , 2 , 3 ]
s. insert ( 2 )
s. insert ( 4 )
print ( s. count )
A 5 B 3 C 4 D 2
2 is already there, so only 4 is added.
Show answer
How do you remove the key "cake" from a dictionary?
A prices.delete("cake") B prices["cake"] = 0 C prices.remove("cake") D prices["cake"] = nil
Assigning nil removes the entry (removeValue(forKey:) also works).
Show answer
Why should you sort keys before printing a dictionary in a test?
A Sorting is faster B Keys must be sorted to be printed C It removes duplicates D Dictionaries are unordered, so their order can change between runs
Sorting gives stable, predictable output.
Show answer
Complete the code so every price is doubled.
let doubled = prices. { $0 * 2 }
map transforms every item into a new array.
Check answer Show solution
print ( [ 1 , 2 , 3 , 4 ] . filter { $0 % 2 == 0 } )
A [2, 4] B [1, 3] C 6 D [true, false, true, false]
filter keeps the even numbers.
Show answer
print ( [ 2 , 3 , 4 ] . reduce ( 1 , * ) )
A 9 B 10 C 24 D 1
Start with 1 and multiply by each item: 1 x 2 x 3 x 4.
Show answer
What does $0 mean inside a closure?
A The closure's return value B The number zero C The closure's first argument D The array's first item, always
$1 is the second argument, and so on.
Show answer
When must a closure parameter be marked @escaping?
A When the closure may run after the function has returned, for example stored or used as a completion handler B Always C When it has more than one parameter D When it returns a value
Non-escaping closures run during the call.
Show answer
Complete the method so it can change the struct's property.
struct Counter {
var count = 0
func reset ( ) { count = 0 }
}
Methods that change a struct's properties must be marked mutating.
Check answer Show solution
struct Box { var w: Int ; var h: Int ; var area: Int { w * h } }
print ( Box ( w: 3 , h: 4 ) . area )
A 12 B 7 C 34 D An error
area is computed from w and h.
Show answer
struct P { var x: Int }
var a = P ( x: 1 )
var b = a
b. x = 5
print ( a. x + b. x )
A 6 B 10 C 2 D 5
b is an independent copy, so a.x is still 1.
Show answer
A An optional property B An initializer with no parameters C A failable initializer that can return nil for invalid input D A default initializer
Callers get an optional instance.
Show answer
When does Apple recommend using a struct instead of a class?
A Never B Only for numbers C Only for SwiftUI views D By default, unless you need shared identity, inheritance or reference behaviour
Value types are simpler to reason about.
Show answer
Complete the subclass method so it replaces the parent's version.
class Cat : Animal {
func sound ( ) -> String { "Meow" }
}
override is required when replacing an inherited method.
Check answer Show solution
What kind of type is a class?
A A value type B A reference type C A protocol D An enum
Variables share a reference to one object.
Show answer
class Box { var n = 1 }
let a = Box ( )
let b = a
b. n = 7
print ( a. n )
A 7 B 1 C 8 D An error
a and b refer to the same object.
Show answer
A Whether two values are equal B Whether two types match C Whether two references point to the same object D Whether an object is nil
== compares values and needs Equatable.
Show answer
Why can you call a method that changes properties on a let class instance?
A Classes ignore let B Methods are always mutating C It's a compile error D let only fixes which object the constant refers to; the object's var properties can still change
Structs behave differently: a let struct can't change at all.
Show answer
Fill in the blankseasy Enums Complete the declaration so the enum gets an allCases list.
enum Weekday : {
case mon, tue, wed, thu, fri
}
CaseIterable provides allCases.
Check answer Show solution
Predict the outputeasy Enums
enum Coin : Int { case penny = 1 , nickel = 5 , dime = 10 }
print ( Coin . dime . rawValue )
A dime B 2 C 10 D Coin.dime
rawValue gives the value assigned to the case.
Show answer
Multiple choicemedium Enums What type does Size(rawValue: "XL") return?
A Size B String C Bool D Size? (optional)
The text might not match any case.
Show answer
Predict the outputmedium Enums
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)
}
A 28.26 B 9.0 C 3.0 D square
The square case matches and its side is 3.0.
Show answer
Why avoid default when switching over your own enum?
A default is slower B default isn't allowed with enums C It changes the raw values D Without default, adding a new case makes every incomplete switch a compile error
The compiler then finds every switch that needs updating.
Show answer
Complete the declaration so Book conforms to Describable.
struct Book Describable {
let title: String
func describe ( ) -> String { title }
}
Protocol conformance follows a colon after the type name.
Check answer Show solution
Which types can conform to protocols?
A Only classes B Only structs C Structs, classes and enums D Only enums
Any named type can adopt protocols.
Show answer
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 ( ) )
A Hello Bonjour B Hello Hello C Bonjour Bonjour D An error
English uses the default; French provides its own.
Show answer
What does adding Equatable to a struct with Equatable properties give you?
A Sorting B An automatically generated == operator C JSON support D An id property
Swift synthesises the comparison.
Show answer
What's the difference between some View and any View?
A There's none B any is faster C some is only for classes D some means one specific concrete type hidden from the caller; any means any conforming type, which can vary
SwiftUI's body uses some View.
Show answer
Complete the code so every Int gets an isPositive property.
Int {
var isPositive: Bool { self > 0 }
}
extension adds functionality to an existing type.
Check answer Show solution
extension Int { var squared: Int { self * self } }
print ( 6 . squared )
A 12 B 6 C 36 D An error
self is 6, and 6 times 6 is 36.
Show answer
What can't an extension add?
A Stored properties B Computed properties C Methods D Protocol conformance
Stored properties would change a type's memory layout.
Show answer
extension Array where Element == Int { var total: Int { reduce ( 0 , + ) } }
print ( [ 4 , 5 , 6 ] . total )
A [4, 5, 6] B 3 C An error D 15
The constrained extension adds up the Ints.
Show answer
Why add an initializer to a struct in an extension rather than in the struct itself?
A The struct keeps its automatic memberwise initializer as well as the new one B Extensions run faster C Initializers can only go in extensions D It makes the struct a class
Defining init inside the struct would remove the memberwise initializer.
Show answer
Complete the call to a throwing function.
do {
let data = loadFile ( "notes.txt" )
} catch {
print ( error)
}
Calls that can throw must be marked with try.
Check answer Show solution
Which protocol must a type adopt to be thrown?
A Throwable B Exception C Error D Failure
Enums adopting Error are the usual choice.
Show answer
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 )
A negative B 0 C -3 D A crash
try? turns the thrown error into nil, and ?? supplies 0.
Show answer
When does a defer block run?
A Immediately B Only when an error is thrown C When the current scope exits, whether normally, by return or by a thrown error D Never automatically
It's ideal for clean-up.
Show answer
A For user input B For network requests C Always, it's shorter D Only when failure is impossible, such as decoding a file you ship with the app
A failure crashes the app.
Show answer
Complete the declaration so the function works with any type T.
func wrap( _ value: T) -> [ T] {
[ value]
}
The type parameter goes in angle brackets after the name.
Check answer Show solution
struct Box < Value > { var value: Value }
let b = Box ( value: "hi" )
print ( b. value . count )
A hi B 2 C 1 D An error
Value is inferred as String, so count works.
Show answer
Why does func maxOf<T>(_ a: T, _ b: T) -> T { a > b ? a : b } fail to compile?
A Generics can't return values B T must be a class C The ternary operator isn't allowed D T has no constraint, so Swift doesn't know it supports >
Add T: Comparable.
Show answer
What does associatedtype declare?
A A placeholder type in a protocol that each conforming type fills in B A stored property C A class type D A typealias for Any
Collection's Element is an associated type.
Show answer
What does some View as a return type mean?
A Any view, which can change at run time B An optional view C One specific concrete type conforming to View, known to the compiler but hidden from the caller D A class that inherits from View
It's an opaque return type.
Show answer
Complete the property so it doesn't keep the delegate alive.
class TableView {
var delegate: TableDelegate ?
}
Delegates are weak to avoid reference cycles.
Check answer Show solution
How many times does "Freed" print?
class Item { deinit { print ( "Freed" ) } }
var x: Item ? = Item ( )
var y = x
x = nil
A 1 B 0 C 2 D An error
y still holds a strong reference, so the instance isn't freed.
Show answer
What happens to a weak reference when the object it points to is freed?
A It crashes B It keeps the object alive C It becomes nil automatically D It points to a copy
That's why weak properties must be optional vars.
Show answer
Which types does ARC manage?
A Class instances (and closures) B Structs C Enums D Ints and Strings
Value types are copied, not reference counted.
Show answer
When do you need [weak self] in a closure?
A In every closure B In map and filter C When the closure is stored by the object it refers to, or something the object owns, creating a cycle D Only in structs
Closures that run once and aren't stored don't cause cycles.
Show answer
Complete the call to the async function.
let data = try download ( url)
Async calls are marked with await.
Check answer Show solution
What does marking a function async mean?
A It runs twice as fast B It runs on the main thread C It can suspend while waiting, and callers must use await D It can't throw errors
Other work can run while it waits.
Show answer
Roughly how long does this take?
async let a = wait ( seconds: 2 )
async let b = wait ( seconds: 2 )
_ = await ( a, b)
A 4 seconds B 0 seconds C 1 second D 2 seconds
async let runs both waits at the same time.
Show answer
What does an actor guarantee?
A Only one task at a time can access its mutable state B Its code runs on the main thread C It never suspends D It can't have methods
That prevents data races.
Show answer
Why is SwiftUI's .task modifier often better than Task { } in onAppear?
A It's faster B It runs on a background thread C It doesn't need await D It cancels the work automatically when the view disappears
The task is tied to the view's lifetime.
Show answer
Complete the line that turns JSON data into a Book.
let book = try JSONDecoder ( ) . decode ( , from: data)
decode takes the type to create, written as Type.self.
Check answer Show solution
Which two protocols make up Codable?
A Equatable and Hashable B Reader and Writer C Decodable and Encodable D Input and Output
Codable is a typealias for both.
Show answer
The JSON is {"name": "Ada"}. What happens when it's decoded into struct U: Codable { let name: String; let age: Int? }?
A It succeeds with age set to nil B Decoding fails C age becomes 0 D name becomes nil
Optional properties decode as nil when missing.
Show answer
What does keyDecodingStrategy = .convertFromSnakeCase do?
A Renames your struct B Sorts the keys C Converts numbers to strings D Maps JSON keys like user_id to Swift names like userId
It saves writing CodingKeys for snake_case APIs.
Show answer
If you write CodingKeys for a struct, what must it include?
A Only renamed properties B Only optional properties C A case for every property that should be encoded or decoded D Nothing, it's empty
Properties without a case are skipped, and non-optional skipped ones need default values.
Show answer
Complete the view so it conforms to SwiftUI's View protocol.
struct HelloView : {
var body: some View {
Text ( "Hello" )
}
}
Every SwiftUI view conforms to View and provides a body.
Check answer Show solution
Which stack arranges views from top to bottom?
A HStack B ZStack C List D VStack
V stands for vertical.
Show answer
What does Spacer() do inside an HStack?
A Adds a fixed 8-point gap B Draws a line C Expands to fill the spare space, pushing other views apart D Hides the next view
It's flexible empty space.
Show answer
Which of these gives a coloured box that includes space around the text?
A Text("Hi").background(.blue).padding() B Text("Hi").padding().background(.blue) C Text("Hi").padding(0).background(.blue) D Text("Hi").background(.blue)
Padding must come before background for the colour to cover it.
Show answer
Why does SwiftUI's body return some View rather than a named type?
A The real type is a complex nested generic type; some lets the compiler know it without you writing it B For speed C body can return any type at run time D It makes the view optional
It's an opaque return type.
Show answer
Complete the code to pass a binding to the toggle.
@State private var isOn = false
Toggle ( "Sound" , isOn: isOn)
The $ prefix creates a binding.
Check answer Show solution
Which property wrapper stores simple state owned by a single view?
A @Binding B @Environment C @Bindable D @State
Mark it private, because it belongs to the view.
Show answer
A child view needs to change a value owned by its parent. What should the child declare?
A @State var value B @Binding var value C let value D @Environment var value
A binding reads and writes the parent's state.
Show answer
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?
A 6 B 2 C 3 D 0
Each tap adds 2, and the text updates every time.
Show answer
Where should an @Observable model shared by many screens be created?
A Once, stored with @State in a view near the root, then passed down or put in the environment B In every view that uses it C In a global variable inside each view D In a @Binding
One owner keeps one source of truth.
Show answer
Complete the struct so it can be shown in a List without an id argument.
struct Song : {
let id = UUID ( )
let title: String
}
List and ForEach need Identifiable data.
Check answer Show solution
Which container provides the navigation bar and back button?
A NavigationStack B VStack C List D TabView
NavigationLinks inside it push new screens.
Show answer
How is a sheet usually shown?
A By calling present() B By creating a new window C By setting a @State Boolean bound to .sheet(isPresented:) to true D With NavigationLink
Presentation is driven by state.
Show answer
cities is ["Berlin", "Lisbon", "London"] and the filter keeps names where $0.localizedCaseInsensitiveContains("ON"). How many remain?
A 0 B 1 C 3 D 2
Lisbon and London both contain "on", ignoring case.
Show answer
Why does a value used with navigationDestination(for:) need to be Hashable?
A For JSON B To sort them C Navigation stores values in a path that requires hashable elements D It doesn't
The navigation path is a collection of hashable values.
Show answer
Complete the check inside the test.
@Test func doublesNumbers ( ) {
( double ( 4 ) == 8 )
}
#expect records a failure if the condition is false.
Check answer Show solution
Which attribute marks a function as a test in Swift Testing?
A @Testable B @Check C @Unit D @Test
Test functions are marked with @Test.
Show answer
What's the difference between #expect and try #require?
A There's none B #require is only for XCTest C #expect can only compare numbers D #expect records a failure and continues; #require stops the test immediately and can unwrap optionals
Use #require when later lines depend on the check.
Show answer
How many test results does this produce?
@Test ( arguments: [ 1 , 2 , 3 , 4 ] )
func isPositive ( _ n: Int ) { #expect ( n > 0 ) }
A 4 B 1 C 0 D 2
A parameterised test runs once per argument.
Show answer
Why should a view model take its API through a protocol?
A Protocols are faster B It's required by SwiftUI C Tests can pass in a fake that returns fixed data or errors instantly D To avoid async code
Fakes make tests fast and reliable.
Show answer
A library should expose a struct's construction to another module. What should its author provide?
A Only public on the struct and assume all members become public. B open on the struct. C An explicit public initializer with a supported contract.
A public type does not automatically publish its synthesized memberwise initializer.
Show answer
A form needs to distinguish an empty code from an invalid quantity. Which construction API is useful?
A An initializer that silently creates a default product for every error. B A throwing initializer with descriptive domain errors. C A precondition that terminates for ordinary mistakes.
Throwing construction can preserve validity while giving the caller an actionable failure reason.
Show answer
A changing source must affect every read immediately. Which design most directly expresses that requirement?
A A computed getter based on the current source. B A lazy cached result with no invalidation. C A wrapper that ignores every assignment.
Recalculation from current state avoids retaining an outdated first-access result.
Show answer
A generic function only extracts properties. Which parameter capability is sufficient?
A ReferenceWritableKeyPath for every root. B An unvalidated String field name. C KeyPath<Root, Value>.
Reading does not require writable capability; typed selection catches incompatible properties at compilation.
Show answer
A stable field has exactly three supported alternatives. Which model can make handling exhaustive?
A An arbitrary runtime field-name string. B An enum with associated values for the three alternatives. C Any with forced casts in every caller.
An enum states the allowed cases explicitly and supports compiler-checked switching.
Show answer
Two inputs must share the same concrete conforming type. What expresses that relationship clearly?
A One named generic parameter used for both inputs. B Two unrelated some Protocol parameters with no relation. C Unrestricted Any parameters.
The shared generic parameter encodes the same-type relationship directly.
Show answer
An algorithm only visits elements once and stops after enough matches. Which broad constraint fits?
A RandomAccessCollection solely because Array is common. B A hard-coded zero-based Array requirement. C Sequence, with any needed element constraint.
Basic single-pass iteration does not require indexed random access.
Show answer
Which operation safely selects a visible prefix without assuming fixed-width characters?
A Use indices from an unrelated string. B Use text.prefix(limit), then choose an explicit String storage policy. C Slice raw UTF-8 bytes at an arbitrary offset and force-decode.
Character-level prefix selection respects grapheme boundaries for the stated preview task.
Show answer
A token grammar requires exactly three following digits. What near miss should a search test include?
A ORD1234, to verify that a longer number is not accepted as a shorter prefix. B Only one valid ORD007 example. C A claim that capture types make all boundaries automatic.
Searching can otherwise match the beginning of a longer invalid token.
Show answer
An external package is declared but a target still cannot import its module. What should be checked?
A Only the application's displayed title. B Whether every function was renamed main. C The target's dependency on the correct external product and module name.
Declaring a package source alone does not connect every target to every product.
Show answer
What makes the payment-deadline function reproducible in tests?
A Inheriting whatever default zone exists on the test machine. B Passing a fixed reference moment and explicit calendar context. C Calling Date() privately on every line.
Tests control the temporal inputs rather than depend on the environment's current day.
Show answer
Two callers can update the same file from the same old snapshot. What is still required?
A An explicit writer-coordination and conflict policy. B Only the atomic option, which automatically merges both updates. C A different filename extension with no ownership rule.
Whole-file replacement does not prevent lost updates from competing read-modify-write operations.
Show answer
Which test setup isolates response validation from live service variability?
A Require a public server to return exactly one response forever. B Embed real credentials in the test source. C Inject a transport returning controlled status and payload fixtures.
Deterministic transport inputs make contract boundaries reproducible without external dependencies.
Show answer
A source emits ongoing replaceable state faster than consumption. What needs an explicit choice?
A A claim that yield always waits for processing. B Buffer capacity, drop policy and source-lifetime cleanup. C An unbounded queue by default forever with no review.
Bounded memory and correct termination require deliberate producer-consumer policies.
Show answer
A UI closure needs only a product code from a mutable controller. Which capture is easier to review?
A A suitable immutable code snapshot, with updates left to the UI owner. B The entire controller with all mutable resources. C A forced unchecked annotation on every reference.
Narrow transferable captures reduce shared state and make ownership clearer.
Show answer
Which test reliably checks stale response rejection?
A Sleep for an arbitrary time and hope the old request is slower. B Test only one successful request. C Control completion order so the replacement finishes before the old request.
Explicitly forced ordering verifies the policy without depending on incidental scheduling.
Show answer
What additional evidence is needed after an in-memory current-schema test passes?
A Appropriate on-disk and old-schema migration checks for the product's requirements. B A claim that every historical store now migrates automatically. C Deleting old user data whenever opening fails.
Fresh in-memory behavior does not establish durability or upgrade compatibility.
Show answer
No exercises match those filters.