UIKit Hot Reload Using Xcode 11’s Live Preview

Ethan Diamond 
2 min readJun 29, 2019

One of the biggest splashes from SwiftUI’s announcement was the live preview window to watch your updates take place as you edit your code.

Given Swift’s struggles with compile time, the amount of time this can save you can’t be overstated.

One super interesting side effect of making SwiftUI interop with UIKit is that you can wrap your current UIViewControllers and UIViews so that SwiftUI can use them, and then use SwiftUI previews to see your UIViewControllers rendered without needing to compile. Let’s take a look at what that looks like.

A couple details about this code:

  1. Wrapping your code in #if DEBUG means that code will only be compiled if you’re using a dev configuration (assuming you left that flag in your build settings). This is required so you don’t have extra functionality you accidentally ship to your users.
  2. canImport(SwiftUI) means that the compiler will ignore the code unless the SwiftUI framework is present. This is required because you’re using some classes from SwiftUI.
  3. Extending SomeViewController to implement UIViewControllerRepresentable allows SwiftUI to access and preview SomeViewController.
  4. Adding @available(iOS 13, *) compiles SomeViewController_Previews no matter what, but makes it unavailable at runtime if the target device is running an iOS version lower than 13. This is required since it contains some code only available to iOS 13.
  5. You will have to set your build configuration for your development build to a minimum of iOS 13 for the preview to show up. However, this conversation with one of the Apple devs on the previews team says this requirement will hopefully be removed by the time Xcode 11 ships

And that’s all it takes!

Since we don’t use storyboards in our codebase, previews are going to be an excellent tool not just for development, but also for discoverability. We’re planning on requiring them on all new UIViewControllers going forward.

Is that a good idea? Bad idea? Let me know what you think on Twitter: @ethanjdiamond.