Skip to content

Latest commit

 

History

History
32 lines (26 loc) · 801 Bytes

ConditionalRendering.md

File metadata and controls

32 lines (26 loc) · 801 Bytes

Conditional Rendering with Optionals

This is a silly thing that confused me when first using SwiftUI. How do you render views when state is optional? In React, it's super easy:

function Example() {
  const [profile, setProfile] = useState(null);

  return (
    <React.Fragment>
      {profile && <ProfileView profile={profile} />}
    </React.Fragment>
  );
}

In SwiftUI you can check if the value is nil. If it's not, you can render the profile and force unwrap the optional value (profile, in this case).

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

    // fetch method
}