EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Swift

Swift Interview Questions and Answers

Computer Science / Swift tutorial chapter - Published 2025-12-16 - Swift

1. What is the difference between a class and a structure in Swift?

Answer:

  • Class: Reference type, supports inheritance, uses reference counting, mutable properties by default.
  • Structure: Value type, no inheritance, copied on assignment, properties are immutable unless declared with var.

2. Explain the purpose of guard in Swift.

Answer:
guard is used for early exit from a function or loop when a condition is not met. It enhances code readability by avoiding nested code.

func checkAge(_ age: Int?) {
    guard let age = age, age >= 18 else {
        print("You must be at least 18 years old.")
        return
    }
    print("You are eligible.")
}

3. What is the difference between mapflatMap, and compactMap?

Answer:

  • map: Transforms each element and returns an array of optional values.
  • flatMap: Flattens nested collections or removes nil values when used on optionals.
  • compactMap: Returns a new array with non-nil values after transformation.

4. What are protocol extensions, and how are they useful?

Answer:
Protocol extensions allow you to provide default implementations of methods or properties in protocols, enabling code reuse and avoiding duplicate code across conforming types.

5. Explain what defer does in Swift.

Answer:
defer executes a block of code just before the current scope exits, ensuring cleanup or finalization.

func readFile() {
    let file = openFile("example.txt")
    defer {
        closeFile(file)
    }
    // File operations
}
End of lesson.