Skip to content
DeveloperMemos

Using the New '#Preview' Macro with XCode 15(iOS 17)

XCode 15, SwiftUI, iOS 17, Code Preview1 min read

I may be a bit late to the party, but I wanted to shed some light on an exciting new feature in XCode 15. As a frequent user of SwiftUI, I often found it cumbersome to repeatedly write boilerplate code for previews. In the past, creating a preview for a SwiftUI view involved defining a separate PreviewProvider struct and specifying the view to be previewed within it. This process, while necessary, could become tedious, especially when working on projects with numerous views.

The Old Preview Syntax

To provide some context, here's how the old preview syntax used to look:

1struct HomeView_Previews: PreviewProvider {
2 static var previews: some View {
3 HomeView()
4 .environmentObject(UserStore())
5 }
6}

While this method served its purpose, it left room for improvement in terms of simplicity and readability.

The Game Changer: #Preview Macro

Enter the new #Preview macro, a game-changer in XCode 15. With this addition, SwiftUI developers can streamline the process of creating previews, making it more concise and readable. Here's how the previous example can be rewritten using the #Preview macro:

1#Preview {
2 HomeView()
3 .environmentObject(UserStore())
4}

This enhancement not only simplifies the code but also significantly enhances its readability.

Compatibility Beyond iOS 17

One of the most significant advantages of the #Preview macro is its compatibility with older project versions. Even if your project targets an iOS version prior to 17.0, you can still take advantage of this feature. I tested this functionality by incorporating the #Preview macro into a project targeting iOS 15.0, and I encountered no issues when building, running, or archiving the project.

Improved Autocompletion for SwiftUI Views

In addition to the #Preview macro, XCode 15 brings another notable enhancement for SwiftUI developers. When creating a new SwiftUI view, XCode now offers improved autocompletion for generating the initial boilerplate code. When you begin defining a view with something like struct TesterView: View, the first autocomplete suggestion will assist you in completing the remaining boilerplate code:

1struct TesterView: View {
2 var body: some View {
3 Text("Hello, world!")
4 }
5}

This streamlined workflow makes it even more convenient to start building SwiftUI views. Definitely try it out for yourself when you get a chance!