[Pitch] Primary Associated Types in the Standard Library

Interacting with a clock seems to require knowledge of its Instant.Duration, right? Otherwise you have no way of referring to an advanced instant, or how to tell it to sleep to a certain instant.

So it sounds appropriate for Clock's primary associated type to be this associated type of its Instant. Similar to how Collection<Element> shares its primary associated type with its Iterator.

Having Clock<Duration> would allow you to tell an arbitrary clock to sleep so long as you know its primary associated type, which is particularly useful for writing testable, time-based code, where your application logic can be injected with some Clock<Duration>: it can take a ContinuousClock when run in release, and a theoretical TestClock that can be manually advanced in your tests.

In Combine Schedulers we needed to parameterize a type-erased scheduler (AnyScheduler) and TestScheduler over the SchedulerTimeType in order to inject testable schedulers into application code. It would seem that without a primary associated type on Clock, anyone that would want to do something similar would need to still resort to bespoke wrapper types, like AnyClock.

4 Likes