15 June 2020 2min read

Shared SwiftUI previews for prototyping

The introduction of SwiftUI and previews changed completely my process of developing applications. Having such an easy way of quickly prototyping UI ideas affected the rest of my process. But as much as I love Xcode previews, they are not perfect. In this post I want to share with you a small trick that can improve a lot your iteration cycles.

One small inconvenience (well, not so small since I’m writing about it) is the amount of places you need to change the code to make it compile after a change.

As an example lets take a look at the code that is given to us by Xcode’s default templates.

The SceneDelegate has code to initialise the root view of your application:

...
let contentView = ContentView()
...

And the same code can be found in the PreviewProvider of that ContentView:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

This can become quite an annoyance since every time that you change your ContentView initialiser, or any other change that affects the shape of your view types, you have to tweak the code in the scene delegate and in the preview provider.

In early stages of development, while you’re still discovering your application, this can happen quite often. My personal recommendation is that you change this structure until you’re comfortable enough with your app that you don’t do such foundational changes that often.

The trick is simple. Just treat your preview code as the source of truth.

Change the line on your scene delegate to:

let contentView = ContentView_Previews.previews

In this way, every change that your view needs will only need to be done in the preview code. This makes the iteration cycles even faster, which is crucial on that discovery phase.

Screenshot

If you want to make sure that you don’t ship preview code to your users you can just surround that line with an #if DEBUG and use the real view initialiser on release.

I hope this little trick serves you well ;)

If you enjoyed this post

Continue reading