From a2c6a0341e9dd6fe8b91be0677f17af06bbde50c Mon Sep 17 00:00:00 2001 From: "Alkenso (Vladimir Vashurkin)" Date: Mon, 9 Dec 2024 14:16:20 +0200 Subject: [PATCH] Improve Synchronized.initialize method for Optionals --- .../Threading & Concurrency/Atomic.swift | 12 ------------ .../Threading & Concurrency/Synchronized.swift | 8 ++++++-- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/Sources/SpellbookFoundation/Threading & Concurrency/Atomic.swift b/Sources/SpellbookFoundation/Threading & Concurrency/Atomic.swift index f547bfe..3a76084 100644 --- a/Sources/SpellbookFoundation/Threading & Concurrency/Atomic.swift +++ b/Sources/SpellbookFoundation/Threading & Concurrency/Atomic.swift @@ -47,18 +47,6 @@ public final class Atomic { public func exchange(_ value: Value) -> Value { storage.write { updateSwap(&$0, value) } } - - public func initialize(_ 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 { diff --git a/Sources/SpellbookFoundation/Threading & Concurrency/Synchronized.swift b/Sources/SpellbookFoundation/Threading & Concurrency/Synchronized.swift index bb22abb..c67bfa5 100644 --- a/Sources/SpellbookFoundation/Threading & Concurrency/Synchronized.swift +++ b/Sources/SpellbookFoundation/Threading & Concurrency/Synchronized.swift @@ -112,17 +112,21 @@ extension Synchronized { self.init(primitive, nil) } - public func initialize(_ initialize: @autoclosure () throws -> T) rethrows -> T where Value == T? { + public func initialize(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(_ value: T) -> T where Value == T? { + initialize { value } + } } public extension Synchronized where Value: AdditiveArithmetic {