Last active
April 24, 2018 14:31
-
-
Save Gatada/82b460ad065328818677b1438daca5ce to your computer and use it in GitHub Desktop.
How to make a singleton fully testable (resettable)?
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 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