Created
April 13, 2017 15:38
-
-
Save sundeepgupta/a8d0a30abf71e52f16c7c395e359f913 to your computer and use it in GitHub Desktop.
Swift thread-safe dependency injection
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 | |
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