Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sundeepgupta/a8d0a30abf71e52f16c7c395e359f913 to your computer and use it in GitHub Desktop.
Save sundeepgupta/a8d0a30abf71e52f16c7c395e359f913 to your computer and use it in GitHub Desktop.
Swift thread-safe dependency injection
import Foundation
protocol HatType { }
class Hat: HatType {
init() {
print("real hat 1")
}
}
class Hat2: HatType {
init() {
print("real hat 2")
}
}
struct HatInjector {
private static let queue = DispatchQueue(label: "HatInjector.queue")
private static var _hat: HatType?
static var hat: HatType {
get {
guard _hat == nil else { return _hat! }
queue.sync {
guard _hat == nil else { return }
_hat = Hat2()
}
return _hat!
}
set { queue.sync { _hat = newValue } }
}
}
DispatchQueue.global().async {
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
HatInjector.hat
}
}
DispatchQueue.global().async {
DispatchQueue.concurrentPerform(iterations: 1000, execute: { _ in
HatInjector.hat = Hat()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment