Browse Questions
  • Protocol extensions let you add default implementations to protocol methods, so conforming types get behavior for free without inheriting from a base class.
  • A race condition occurs when two or more threads access shared mutable state simultaneously, producing unpredictable results depending on timing.
  • | Problem | Cause | Fix | |---------|-------|-----| | #if SIT always falls through to #else | Flag added to Other Swift Flags instead of Active Compilation Conditions | Move flag to the correct…
  • A Task is Swift's unit of async work.

Answer: A race condition occurs when two or more threads access shared mutable state simultaneously, producing unpredictable results depending on timing.

Code Example:

// ❌ Race condition — counter could be corrupted
class UnsafeCounter {
    var count = 0
    func increment() { count += 1 }  // not thread-safe
}

// ✅ Option 1 — Use an actor (preferred in modern Swift)
actor SafeCounter {
    var count = 0
    func increment() { count += 1 }  // actor serializes access
}

// ✅ Option 2 — Serial dispatch queue
class QueueCounter {
    private var count = 0
    private let queue = DispatchQueue(label: "com.app.counter")

    func increment() {
        queue.async { self.count += 1 }
    }

    func value(completion: @escaping (Int) -> Void) {
        queue.async { completion(self.count) }
    }
}