Skip to content

Instantly share code, notes, and snippets.

@jeandavid
Last active July 30, 2018 08:45
Show Gist options
  • Save jeandavid/dd07b91563a7aa8616e462242537ae01 to your computer and use it in GitHub Desktop.
Save jeandavid/dd07b91563a7aa8616e462242537ae01 to your computer and use it in GitHub Desktop.
Singleton Pattern in Swift
//
// UserSingleton.swift
//
//
// Created by Jean-David Morgenstern-Peirolo on 7/30/18.
//
import Foundation
final class UserSingleton {
// A static type property (constant or variable) is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously
public static let sharedInstance: UserSingleton = {
let instance = UserSingleton()
return instance
}()
private init() {}
private var _count: Int = 0
private var _likes: Int = 0
private let serialQueue = DispatchQueue(label: "UserSingletonSerialQueue")
private let concurrentQueue = DispatchQueue(label: "UserSingletonConcurrentQueue", qos: .default, attributes: .concurrent)
// https://developer.apple.com/videos/play/wwdc2016/720/
public var count: Int {
get {
return serialQueue.sync {
_count
}
}
set (newCount) {
// serial queue -> safe writes!
serialQueue.async {
self._count = newCount
}
}
}
public var likes: Int {
get {
// Read concurrently
return concurrentQueue.sync {
_likes
}
}
set (newLikes) {
// A dispatch barrier ensures that a piece of code will be executed, and while it’s being executed, no other piece of code will be executed
// Writes are executed exclusively
concurrentQueue.async(flags: .barrier) {
self._likes = newLikes
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment