Skip to content

Instantly share code, notes, and snippets.

@lnfnunes
Created June 25, 2021 20:43
Show Gist options
  • Save lnfnunes/764c4ae61d4e27deac2ed4314ae6fd6b to your computer and use it in GitHub Desktop.
Save lnfnunes/764c4ae61d4e27deac2ed4314ae6fd6b to your computer and use it in GitHub Desktop.
Atomic decorator (Swift - Property Wrapper)
//
// Atomic.swift
// Rewards
//
// Created by Leandro Nunes Fantinatto on 16/06/21.
// Copyright © 2021 Anheuser-Busch InBev. All rights reserved.
//
import Foundation
@propertyWrapper
struct Atomic<Value> {
private let lock = DispatchSemaphore(value: 1)
private var value: Value
init(defaultValue: Value) {
self.value = defaultValue
}
var wrappedValue: Value {
get {
lock.wait()
defer { lock.signal() }
return value
}
set {
lock.wait()
value = newValue
lock.signal()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment