Skip to content

Instantly share code, notes, and snippets.

@oconnelltoby
Created September 12, 2021 12:26
Show Gist options
  • Save oconnelltoby/6e1128073be3eef7f95f5a259dfcc490 to your computer and use it in GitHub Desktop.
Save oconnelltoby/6e1128073be3eef7f95f5a259dfcc490 to your computer and use it in GitHub Desktop.
Demonstration of a mocked Timer
import Foundation
protocol Timing {
associatedtype TimerType: Timing
static func scheduledTimer(withTimeInterval: TimeInterval, repeats: Bool, block: @escaping (TimerType) -> Void) -> TimerType
func invalidate()
func fire()
}
extension Timer: Timing {}
struct MockTimer: Timing {
typealias TimerType = Self
static var timerCreated: ((Self) -> Void)?
var timeInterval: TimeInterval
var repeats: Bool
var block: (Self) -> Void
var mockInvalidate: () -> Void
static func scheduledTimer(
withTimeInterval timeInterval: TimeInterval,
repeats: Bool,
block: @escaping (TimerType) -> Void
) -> TimerType {
var invalidatableBlock: ((TimerType) -> Void)? = block
let timer = MockTimer(
timeInterval: timeInterval,
repeats: repeats,
block: { invalidatableBlock?($0) },
mockInvalidate: { invalidatableBlock = nil }
)
timerCreated?(timer)
return timer
}
func invalidate() {
mockInvalidate()
}
func fire() {
block(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment