ThreadLocalValue
public struct ThreadLocalValue<T: Any>
Provides a type-safe mechanism for accessing thread-local values (of type T
)
stored in the threadDictionary
associated with the calling thread.
As the class name implies, values set using ThreadLocalValue
are only visible
to the thread that set those values.
-
If the receiver was initialized with a
namespace
, this property will contain that value.Declaration
Swift
public let namespace: String?
-
The signature of a function to be used for providing values when none exist in the
current
thread’sthreadDictionary
.Declaration
Swift
public typealias ValueProvider = (ThreadLocalValue) -> T?
-
Initializes a new instance referencing the thread-local value associated with the specified key.
Declaration
Swift
public init(key: String, valueProvider: @escaping ValueProvider = { _ in return nil })
Parameters
key
The key used to access the value associated with the receiver in the
threadDictionary
.valueProvider
A
ValueProvider
function used to provide a value when the underlyingthreadDictionary
does not contain a value. -
Initializes a new instance referencing the thread-local value associated with the specified namespace and key.
Declaration
Swift
public init(namespace: String, key: String, valueProvider: @escaping ValueProvider = { _ in return nil })
Parameters
namespace
The name of the code module that will own the receiver. This is used in constructing the
fullKey
.key
The key within the namespace. Used to construct the
fullKey
associated with the receiver.valueProvider
A
ValueProvider
function used to provide a value when the underlyingthreadDictionary
does not contain a value. -
Retrieves the
current
thread’sthreadDictionary
value associated with the receiver’sfullKey
. If the value isnil
or if it is not of typeT
, the receiver’svalueProvider
will be consulted to provide a value, which will be stored in thethreadDictionary
using the keyfullKey
.nil
will be returned if no value was provided.Declaration
Swift
public var value: T?
-
Sets a new value in the
current
thread’sthreadDictionary
for the key specified by the receiver’sfullKey
property.Declaration
Swift
public func set(_ newValue: T?)
Parameters
newValue
The new thread-local value.