iOS Development Swift Programming Language 2 — Questions and Answers
Question 1: What is protocol-oriented programming in Swift?
- Designing code around protocol definitions rather than class hierarchies (Correct answer)
- Using only value types in your code
- Avoiding the use of generics
- Subclassing UIViewController for every screen
Correct answer: Designing code around protocol definitions rather than class hierarchies
Protocol-oriented programming in Swift emphasizes defining behavior through protocols rather than relying on class inheritance.
Question 2: Which access control level in Swift restricts access to the same file?
- fileprivate (Correct answer)
- private
- internal
- public
Correct answer: fileprivate
`fileprivate` restricts the use of an entity to the same Swift source file where it is defined.
Question 3: What does `@escaping` mean on a closure parameter in Swift?
- The closure can be stored and called after the function returns (Correct answer)
- The closure cannot capture self
- The closure runs synchronously
- The closure throws errors
Correct answer: The closure can be stored and called after the function returns
An `@escaping` closure is allowed to outlive the function it was passed into, commonly used for async callbacks.
Question 4: What is a Swift struct compared to a class?
- A value type that is copied on assignment (Correct answer)
- A reference type that is shared on assignment
- A type that supports inheritance
- A type that cannot have methods
Correct answer: A value type that is copied on assignment
Swift structs are value types, so they are copied whenever they are assigned to a new constant, variable, or passed to a function.
Question 5: Which Swift operator is used for nil-coalescing?
- ?? (Correct answer)
- ?!
- ||
- !?
Correct answer: ??
The nil-coalescing operator `??` unwraps an optional and provides a default value if the optional is nil.
Question 6: What is the purpose of the `defer` statement in Swift?
- Executes a block of code just before the current scope exits (Correct answer)
- Delays initialization of a property
- Marks a function as asynchronous
- Skips execution of the next statement
Correct answer: Executes a block of code just before the current scope exits
`defer` schedules a block of code to run when the current scope (function, loop body, etc.) exits, regardless of how it exits.
What is protocol-oriented programming in Swift?