Atomic.swift 679 B

12345678910111213141516171819202122232425262728293031323334353637
  1. //
  2. // Atomic.swift
  3. // Broadcast Extension
  4. //
  5. // Created by Maksym Shcheglov.
  6. // https://www.onswiftwings.com/posts/atomic-property-wrapper/
  7. //
  8. import Foundation
  9. @propertyWrapper
  10. struct Atomic<Value> {
  11. private var value: Value
  12. private let lock = NSLock()
  13. init(wrappedValue value: Value) {
  14. self.value = value
  15. }
  16. var wrappedValue: Value {
  17. get { load() }
  18. set { store(newValue: newValue) }
  19. }
  20. func load() -> Value {
  21. lock.lock()
  22. defer { lock.unlock() }
  23. return value
  24. }
  25. mutating func store(newValue: Value) {
  26. lock.lock()
  27. defer { lock.unlock() }
  28. value = newValue
  29. }
  30. }