Dependency inversion, SwiftUI previews

I'm trying to find a way to minimize the compile time of SwiftUI view previews. I've heard that applying dependency inversion can help create a boundary and can prevent unnecessary compilation.


If A -> C, any changes made in C would force A to recompile.

However, if you introduce a protocol B, such that:

  • A -> B (A depends on B)
  • B <- C (C adopts B)

Any changes to C will not recompile A, since A's contract with B is unchanged.

Based on that understanding, having SwiftUI views depend on abstract types (protocols) could reduce the compilation times of Xcode previews.

Is that understanding correct?

Kevin Cathey talks about this in WWDC 2020 Session 10149: Structure your app for SwiftUI previews.

Point-Free has also been discussing this in their current series of episodes, “Designing Dependencies”, except that, due to a mild protocol allergy, they use a struct full of closures instead.