I had this implementation with Swift 2.0 and the Xcode suggestion is not only baffling but causes compilation error as well. it\'s a library where users are passing callfunc
The answers to date are great, but I like to be able to test my classes that use singleton with unit tests. The existing solutions require that you get a real singleton, not one that you can Fake, Mock, and Stub. In order to make testing easier, I use something like this:
protocol ScheduleManaging {
func add(_ schedule: TimerSchedule)
}
class ScheduleManager: ScheduleManaging {
var schedule: TimerSchedule?
static var sharedInstance: ScheduleManaging = {
return ScheduleManager()
}()
private init() {
}
}
typealias ScheduleManagingMethods = ScheduleManager
extension ScheduleManagingMethods {
func add(_ schedule: TimerSchedule) {
self.schedule = schedule
}
}
In classes under test that use the singleton, I can do something like this:
class OtherTests: XCTestCase {
class FakeSharedManager: ScheduleManaging {
var addMethodCalled = false
func add(_ schedule: TimerSchedule) {
addMethodCalled = true
}
}
func test_SomeMethodThatShouldCallAdd_CallsAdd() {
ScheduleManager.sharedInstance = FakeSharedManager()
// Test that some class that uses the ScheduleManager
// calls the "add" method of the ScheduleManager
let someClass = ManagerUsingClass()
someClass.someMethodThatShouldCallAdd()
XCTAssertTrue(ScheduleManager.sharedInstance. addMethodCalled)
}
}