Skip to content

Instantly share code, notes, and snippets.

@sidepelican
Created November 3, 2022 08:30
Show Gist options
  • Save sidepelican/467443fdf92a40267f2bd5fe1724fc0d to your computer and use it in GitHub Desktop.
Save sidepelican/467443fdf92a40267f2bd5fe1724fc0d to your computer and use it in GitHub Desktop.
@ThreadLocal property wrapper
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