Skip to content

Instantly share code, notes, and snippets.

@Gatada
Last active April 24, 2018 14:31
Show Gist options
  • Save Gatada/82b460ad065328818677b1438daca5ce to your computer and use it in GitHub Desktop.
Save Gatada/82b460ad065328818677b1438daca5ce to your computer and use it in GitHub Desktop.
How to make a singleton fully testable (resettable)?
import UIKit
import PlaygroundSupport
class SingleInstance {
#if TESTING
open static var shared = SingleInstance()
static func reset() {
SingleInstance.shared = SingleInstance()
}
#else
public static let shared = SingleInstance()
#endif
private init() {}
func greeting() {
print("hello from \(String.pointer(self))")
}
}
// But how to re-instantiate the SingleInstance?
extension String {
static func pointer(_ object: AnyObject?) -> String {
guard let object = object else { return "nil" }
let opaque: UnsafeMutableRawPointer = Unmanaged.passUnretained(object).toOpaque()
return String(describing: opaque)
}
}
SingleInstance.shared.greeting()
SingleInstance.reset()
SingleInstance.shared.greeting()
print("done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment