본문 바로가기

프로그래밍/코드 조각

atomic propery in swift

@propertyWrapper
struct Atomic<Value> {
  private var value: Value
  private let lock = NSLock()
  
  init(wrappedValue value: Value) {
    self.value = value
  }
  
  var wrappedValue: Value {
    get { return load() }
    set { store(newValue: newValue) }
  }
  
  func load() -> Value {
    lock.lock()
    defer { lock.unlock() }
    return value
  }
  
  mutating func store(newValue: Value) {
    lock.lock()
    defer { lock.unlock() }
    value = newValue
  }
}

 

사용 예

@Atomic fileprivate var status: Status = .disconnected

 

참고링크: https://www.onswiftwings.com/posts/atomic-property-wrapper/

 

Atomic property wrapper in Swift

Using property wrappers to define atomic properties in Swift

www.onswiftwings.com