Created
September 12, 2021 12:26
-
-
Save oconnelltoby/6e1128073be3eef7f95f5a259dfcc490 to your computer and use it in GitHub Desktop.
Demonstration of a mocked Timer
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 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