Swift Technology & Digital Applications 2 — Questions and Answers
Question 1: Which Swift feature allows a function to accept a varying number of arguments of the same type?
- Optional chaining
- Variadic parameters (Correct answer)
- Generic constraints
- Protocol extensions
Correct answer: Variadic parameters
Variadic parameters are declared with `...` after the type and let a function receive zero or more values of that type as an array.
Question 2: In Swift, what does the `@discardableResult` attribute do?
- Forces the caller to use the return value
- Suppresses the warning when a return value is ignored (Correct answer)
- Marks a function as deprecated
- Allows a function to return multiple values
Correct answer: Suppresses the warning when a return value is ignored
`@discardableResult` tells the compiler not to warn when the caller ignores the function's return value.
Question 3: Which protocol must a Swift type conform to in order to be used as a dictionary key?
- Equatable
- Comparable
- Hashable (Correct answer)
- Identifiable
Correct answer: Hashable
Dictionary keys must conform to `Hashable`, which also implies `Equatable`, so the dictionary can compute and compare hash values.
Question 4: What is the purpose of Swift's `lazy` stored property modifier?
- It makes the property read-only
- It defers initialization until the property is first accessed (Correct answer)
- It marks the property as optional
- It allows the property to be set from any thread
Correct answer: It defers initialization until the property is first accessed
`lazy` properties are not initialized until they are first accessed, which is useful for expensive computations or dependencies on self.
Question 5: In SwiftUI, which modifier is used to react to changes in a state value and perform a side effect?
- .onAppear
- .onChange (Correct answer)
- .task
- .onReceive
Correct answer: .onChange
`.onChange(of:)` triggers a closure whenever the specified value changes, making it the correct choice for value-change side effects.
Question 6: What does the `async`/`await` keyword pair enable in Swift?
- Parallel execution on multiple CPU cores
- Writing asynchronous code in a sequential, readable style (Correct answer)
- Creating background threads manually
- Locking shared resources with a mutex
Correct answer: Writing asynchronous code in a sequential, readable style
`async`/`await` lets developers write asynchronous code that reads like synchronous code, with the compiler managing suspension points.
Question 7: Which Swift type is best suited for representing a value that may be absent without using optionals?
- Result<Success, Failure> (Correct answer)
- Never
- Void
- AnyObject
Correct answer: Result<Success, Failure>
`Result<Success, Failure>` explicitly encodes either a success value or a typed error, making absence and failure semantics explicit without nil.
Which Swift feature allows a function to accept a varying number of arguments of the same type?