Instance Method
shared(forCallerKey:_:)
Returns a shared instance produced by factory, cached for the lifetime of this component.
final func shared<T>(forCallerKey: String = #function, _ factory: () -> T) -> T
Parameters
- forCallerKey
Implicit cache key. Defaults to #function so each computed property yields a stable, unique key. Callers should write shared { Factory() } and let the default supply the key; pass an explicit value only if you have a deliberate reason to share or separate slots beyond per-property keying.
- factory
A closure that creates the instance the first time this call site is hit.
Return Value
The cached instance, or a freshly created one if this is the first call at this site.
Mentioned In
Discussion
The factory closure is invoked at most once per call site; subsequent calls at the same call site return the cached instance. Call sites are keyed on #function, so each computed property in your component gets its own cache slot automatically:
var imageCache: ImageCache {
shared { ImageCache() } // Slot: imageCache
}
var analytics: AnalyticsService {
shared { AnalyticsService() } // Slot: analytics
}
Important
The factory is invoked while sharedInstances is locked. Do not transitively call shared(forCallerKey:_:) on the same component from inside a factory — Mutex is non-recursive and you will deadlock.