Skip to content

Commit

Permalink
Improve Synchronized.initialize method for Optionals
Browse files Browse the repository at this point in the history
  • Loading branch information
Alkenso committed Dec 9, 2024
1 parent 6aa0301 commit a2c6a03
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 14 deletions.
12 changes: 0 additions & 12 deletions Sources/SpellbookFoundation/Threading & Concurrency/Atomic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,6 @@ public final class Atomic<Value> {
public func exchange(_ value: Value) -> Value {
storage.write { updateSwap(&$0, value) }
}

public func initialize<T>(_ initialize: @autoclosure () -> T) -> T where Value == T? {
storage.write {
if let value = $0 {
return value
} else {
let newValue = initialize()
$0 = newValue
return newValue
}
}
}
}

extension Atomic where Value: AdditiveArithmetic {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,17 +112,21 @@ extension Synchronized {
self.init(primitive, nil)
}

public func initialize<T>(_ initialize: @autoclosure () throws -> T) rethrows -> T where Value == T? {
public func initialize<T>(produceValue: () throws -> T) rethrows -> T where Value == T? {
try write {
if let value = $0 {
return value
} else {
let newValue = try initialize()
let newValue = try produceValue()
$0 = newValue
return newValue
}
}
}

public func initialize<T>(_ value: T) -> T where Value == T? {
initialize { value }
}
}

public extension Synchronized where Value: AdditiveArithmetic {
Expand Down

0 comments on commit a2c6a03

Please sign in to comment.