Swift (Mobile Dev) 3 — Questions and Answers
Question 1: What Swift mechanism lets you handle errors thrown by a function?
- guard-let
- do-try-catch (Correct answer)
- if-let
- switch-case
Correct answer: do-try-catch
A `do-try-catch` block calls a throwing function with `try` and catches any Error value in `catch` clauses.
Question 2: In Core Data, which class represents a managed object's schema definition?
- NSManagedObject
- NSEntityDescription (Correct answer)
- NSPersistentContainer
- NSFetchRequest
Correct answer: NSEntityDescription
NSEntityDescription describes an entity's name, attributes, and relationships in the Core Data model.
Question 3: Which SwiftUI view modifier is used to respond to a value change and execute a side effect?
- .onAppear
- .onChange(of:) (Correct answer)
- .task
- .onReceive
Correct answer: .onChange(of:)
.onChange(of:) triggers a closure whenever the specified value changes, making it ideal for reactive side effects.
Question 4: What is the result type of `try?` when the called function throws an error in Swift?
- Never
- Void
- nil (Optional wrapping the type) (Correct answer)
- An Error value
Correct answer: nil (Optional wrapping the type)
Using `try?` converts a throwing expression to an Optional; a thrown error produces nil instead of propagating.
Question 5: Which Xcode instrument is best for detecting retain cycles and memory leaks in a Swift app?
- Time Profiler
- Leaks (Correct answer)
- Network
- Core Data
Correct answer: Leaks
The Leaks instrument traces object allocations and identifies cycles where memory is never freed.
Question 6: In Swift, which access control level restricts a property to being set only within its defining file?
- private
- fileprivate (Correct answer)
- internal
- public
Correct answer: fileprivate
`fileprivate` limits visibility to the source file containing the declaration, unlike `private` which restricts to the enclosing scope.
Question 7: Which SwiftUI container arranges its children along the vertical axis by default?
- HStack
- ZStack
- VStack (Correct answer)
- Grid
Correct answer: VStack
VStack lays out its child views in a top-to-bottom vertical column.
What Swift mechanism lets you handle errors thrown by a function?