Skip to content

Instantly share code, notes, and snippets.

@romainmenke
Last active July 8, 2022 01:20
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save romainmenke/468168b87de2131847cf to your computer and use it in GitHub Desktop.
Save romainmenke/468168b87de2131847cf to your computer and use it in GitHub Desktop.
class Singleton {
// singelton pattern
private static var privateShared : Singleton?
class func shared() -> Singleton {
// make sure we get an instance from the singleton queue
guard let uwShared = read(privateShared) else {
privateShared = Singleton()
return privateShared!
}
return uwShared
}
func destoy() {
// make sure we write on the singleton queue and halt reads
write {
Singleton.privateShared = nil
}
}
private let singletonQueue = dispatch_queue_create("SingletonQueue", DISPATCH_QUEUE_CONCURRENT)
private static let singletonQueue = dispatch_queue_create("SingletonQueue", DISPATCH_QUEUE_CONCURRENT)
// attributes
private var somePrivateAttribute : Int = 0
var someAttribute : Int {
get {
return read(somePrivateAttribute)
}
set(value) {
write {
self.somePrivateAttribute = value
}
}
}
private init() {
print("init singleton")
}
}
// instance read / write
extension Singleton {
private func write(closure:() -> Void) {
dispatch_barrier_sync(singletonQueue) {
closure()
}
}
private func read<T>(value:T) -> T {
var returnValue : T = value
dispatch_sync(singletonQueue) {
returnValue = value
}
return mainQueue(returnValue)
}
private func mainQueue<T>(value:T) -> T {
var returnValue : T = value
dispatch_sync(dispatch_get_main_queue()) {
returnValue = value
}
return returnValue
}
}
// type read / write
extension Singleton {
private static func write(closure:() -> Void) {
dispatch_barrier_sync(singletonQueue) {
closure()
}
}
private static func read<T>(value:T) -> T {
var returnValue : T = value
dispatch_sync(singletonQueue) {
returnValue = value
}
return mainQueue(returnValue)
}
private static func mainQueue<T>(value:T) -> T {
var returnValue : T = value
dispatch_sync(dispatch_get_main_queue()) {
returnValue = value
}
return returnValue
}
}
@jonchoi
Copy link

jonchoi commented May 29, 2019

What version of swift is this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment