Articles and podcasts about Swift development, by John Sundell.

Genius Scan SDK

Presented by the Genius Scan SDK

This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.

Optional SwiftUI views

Remastered on 28 Jun 2021
Discover page available: SwiftUI

Sometimes we might want one of our SwiftUI views to only be constructed and shown in case a certain optional value is available.

For example, let’s say that we’re building a HomeView that should conditionally contain a ProfileView whenever a LogInManager contains a loggedInUser. Before Swift 5.3, that could be quite tricky to express using SwiftUI’s built-in API, but now, we can simply use a standard if let statement to make that happen:

struct HomeView: View {
    @ObservedObject var loginManager: LoginManager

    var body: some View {
        VStack {
            if let user = loginManager.loggedInUser {
    ProfileView(user: user)
}

            ...
        }
    }
}

Another option that works equally well would be to instead use the map operator on our optional loggedInUser value, which we could then directly pass our ProfileView initializer to — like this:

struct HomeView: View {
    @ObservedObject var loginManager: LoginManager

    var body: some View {
        VStack {
            loginManager.loggedInUser.map(ProfileView.init)
            ...
        }
    }
}

A third and final option would be to extract the above expression (or our if let-based version) into a separate, computed property, which can be a great option when building complex views that require a fair amount of computation to construct:

struct HomeView: View {
    @ObservedObject var loginManager: LoginManager

    var body: some View {
        VStack {
            profileView
            ...
        }
    }
    
    private var profileView: some View {
    loginManager.loggedInUser.map(ProfileView.init)
}
}

At the end of the day, each of the above three options will yield the exact same result, so we’re free to pick whichever technique that we find the most appropriate within each given situation.

Genius Scan SDK

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.