DevPrep

All topics › Real interview tasks

An Atomic @propertyWrapper on os_unfair_lock: what's wrong here?

Senior PRO

Task

A colleague proposed an "atomic" wrapper. Find the problems.

@propertyWrapper
struct Atomic<Value> {
    private var value: Value
    private var lock = os_unfair_lock()

    var wrappedValue: Value {
        mutating get {
            os_unfair_lock_lock(&lock)
            defer { os_unfair_lock_unlock(&lock) }
            return value
        }
        set {
            os_unfair_lock_lock(&lock)
            defer { os_unfair_lock_unlock(&lock) }
            value = newValue
        }
    }

    init(wrappedValue: Value) { value = wrappedValue }
}

final class Counter {
    @Atomic var count = 0
}

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store