Created
June 25, 2021 20:43
-
-
Save lnfnunes/764c4ae61d4e27deac2ed4314ae6fd6b to your computer and use it in GitHub Desktop.
Atomic decorator (Swift - Property Wrapper)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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