-
Notifications
You must be signed in to change notification settings - Fork 730
/
Atomic.swift
53 lines (45 loc) · 1.44 KB
/
Atomic.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import Foundation
/// Wrapper for a value protected by an `NSLock`
@propertyWrapper
public class Atomic<T> {
private let lock = NSLock()
private var _value: T
/// Designated initializer
///
/// - Parameter value: The value to begin with.
public init(wrappedValue: T) {
_value = wrappedValue
}
/// The current value. Read-only. To update the underlying value, use ``mutate(block:)``.
///
/// Allowing the ``wrappedValue`` to be set using a setter can cause concurrency issues when
/// mutating the value of a wrapped value type such as an `Array`. This is due to the copying of
/// value types as described in [this article](https://www.donnywals.com/why-your-atomic-property-wrapper-doesnt-work-for-collection-types/).
public var wrappedValue: T {
get {
lock.lock()
defer { lock.unlock() }
return _value
}
}
public var projectedValue: Atomic { self }
/// Mutates the underlying value within a lock.
///
/// - Parameter block: The block executed to mutate the value.
/// - Returns: The value returned by the block.
public func mutate<U>(block: (inout T) -> U) -> U {
lock.lock()
defer { lock.unlock() }
return block(&_value)
}
}
public extension Atomic where T : Numeric {
/// Increments the wrapped `Int` atomically, adding +1 to the value.
@discardableResult
func increment() -> T {
lock.lock()
defer { lock.unlock() }
_value += 1
return _value
}
}