Swift (Mobile Dev) 2 — Questions and Answers
Question 1: Which Swift property wrapper automatically publishes changes to SwiftUI views in Combine-based code?
- @State
- @Published (Correct answer)
- @Binding
- @ObservedObject
Correct answer: @Published
@Published marks a property so that changes automatically broadcast through Combine's ObservableObject protocol.
Question 2: What is the purpose of `@escaping` in a Swift closure parameter?
- It prevents the closure from capturing self
- It marks the closure as non-optional
- It allows the closure to outlive the function call (Correct answer)
- It makes the closure run on the main thread
Correct answer: It allows the closure to outlive the function call
@escaping tells the compiler the closure may be stored or called after the enclosing function returns.
Question 3: In UIKit, which method must you call to ensure UI updates happen on the correct thread?
- DispatchQueue.global().async
- DispatchQueue.main.async (Correct answer)
- Thread.detachNewThread
- RunLoop.main.run
Correct answer: DispatchQueue.main.async
UIKit is not thread-safe, so all UI mutations must be dispatched to DispatchQueue.main.
Question 4: Which Swift concurrency keyword suspends execution until an async function returns a result?
- async
- await (Correct answer)
- Task
- defer
Correct answer: await
`await` pauses the current async context until the called async function produces its result.
Question 5: What does the `lazy` keyword do when applied to a stored property in Swift?
- Makes the property thread-safe
- Marks it as optional
- Delays initialization until first access (Correct answer)
- Prevents subclasses from overriding it
Correct answer: Delays initialization until first access
A `lazy` stored property's initializer runs only when the property is first accessed, not at instance creation.
Question 6: In SwiftUI, which modifier correctly passes a two-way binding into a child view?
- $variable (Correct answer)
- &variable
- *variable
- #variable
Correct answer: $variable
Prefixing a @State or @StateObject variable with `$` produces a Binding<T> for two-way data flow.
Question 7: Which Foundation class is most appropriate for making HTTP network requests in Swift without third-party libraries?
- NSConnection
- URLSession (Correct answer)
- HTTPClient
- NetworkStream
Correct answer: URLSession
URLSession is Apple's built-in API for performing HTTP/HTTPS data tasks, uploads, and downloads.
Which Swift property wrapper automatically publishes changes to SwiftUI views in Combine-based code?