Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional rendering with optionals in SwiftUI

Tags:

swift

swiftui

Coming from a React background it's easy to only render a view if a value is defined. It looks like this:

function Component ({ profile }) {
  return (
    <div>{profile && <div>{profile.name}}</div>
  )
}

But I'm finding this pattern much more difficult to replicate in SwiftUI. Ideally we could use conditional unwrapping in our Views, but this doesn't currently work. The only solution I've been able to figure out is really inelegant:

struct ProfileView : View {
    var profile: Profile?

    var body : some View {
        if let profile = profile {
            return Text("profile: \(profile.bio)")
        }  else {
            return Text("")
        }
    }
}

struct LayoutView : View {
    @State var profile: Profile?
    var body : some View {
        Group {
            ProfileView(profile: profile)
        }
    }.onAppear(perform: fetch)

    // fetch method 
}

Does anyone have some better strategies for conditional rendering using optional values?

like image 439
bento Avatar asked Jun 14 '19 22:06

bento


1 Answers

You can go the other way around using map to take care of the optional with something like this:

struct ProfileView : View {
    var profile: Profile?

    var body : some View {
        profile.map { Text("profile: \($0.bio)") }
    }
}

($0 is your unwrapped profile in this example.)

If you need the else case:

profile.map { Text($0.bio) } ?? Text("Not available")
like image 82
Ludovic Landry Avatar answered Sep 22 '22 12:09

Ludovic Landry