Using SwiftUI in an existing code base

peterwitham

Peter Witham

Posted on July 1, 2019

Using SwiftUI in an existing code base

originally posted on peterwitham.com

SwiftUI might be the new kid in town when it comes to layout frameworks on Apple platforms. But, that does not mean you need to jump all in right away. You can use the new views in your existing Objective-C and Swift code bases, or vice-versa, add your old views to a new SwiftUI based application.

This enables developers to start using the new technology without having to commit to a complete rebuild/rewrite of the code base. This is an important point, rarely are companies or teams ever in a position to just start over without a large commitment of time or hiring another team to work alongside the existing team. The reason is simple, current production applications still have to be worked on and maintained.

If you are an independent developer then you certainly have a better opportunity to just switch, but this will often cause expected issues.

The ability to use SwiftUI alongside existing code bases is due to something called a HostingController, think of it as a way to contain your views in your application.

If you create a new application using SwiftUI in Xcode 11, you can see the HostingController in action. Just take a look in the SceneDelegate.

To utilize the HostingController you need to provide it just one argument, the name of the view you want to display. For example,

UIHostingController(rootView: ContentView())
Enter fullscreen mode Exit fullscreen mode

Each of Apple’s platforms has its own version of the controller.

macOS uses NSHostingController
iOS uses UIHostingController
watchOS uses WKHostingController

It is worth noting that on watchOS you have to subclass WKHostingController.

If you want to do the reverse and host existing views in a SwiftUI based application then you take advantage of another new technology which is the Representable Protocol. Again, there is a different way on each platform but it is minor.

macOS uses NSViewRepresentable
iOS uses UIViewRepresentable
watchOS uses WKInterfaceObject

You are not limited to views, you can also use existing ViewControllers by using UIViewControllerRepresentable or NSViewControllerRepresentable.

Interestingly, this is not limited to Swift, if you have an Objective-C code base you can integrate them by wrapping the HostingController in Swift using the @objc.

The Wrap

So get to it, there is very little reason to not at least take a look at the new SwiftUI and see if it might be an option for you going forward.

💖 💪 🙅 🚩
peterwitham
Peter Witham

Posted on July 1, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related