Articles, podcasts and news about Swift development, by John Sundell.

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.