Created
November 3, 2022 08:30
-
-
Save sidepelican/467443fdf92a40267f2bd5fe1724fc0d to your computer and use it in GitHub Desktop.
@ThreadLocal property wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
@propertyWrapper | |
public struct ThreadLocal<Value> { | |
private let defaultValue: () -> Value | |
private let name: String | |
public init(wrappedValue: @autoclosure @escaping () -> Value) { | |
self.defaultValue = wrappedValue | |
self.name = UUID().uuidString | |
} | |
public var wrappedValue: Value { | |
get { | |
let dict = Thread.current.threadDictionary | |
if let value = dict[name] { | |
return value as! Value | |
} | |
let value = defaultValue() | |
dict[name] = value | |
return value | |
} | |
set { | |
let dict = Thread.current.threadDictionary | |
dict[name] = newValue | |
} | |
} | |
@available(*, unavailable, message: "Use ThreadLocal to static property.") | |
public static subscript( | |
_enclosingInstance object: Never, | |
wrapped wrappedKeyPath: ReferenceWritableKeyPath<Never, Value>, | |
storage storageKeyPath: ReferenceWritableKeyPath<Never, Self> | |
) -> Value { | |
get { } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment