在 SwiftUI 中使用选项进行条件渲染

ben*_*nto 7 swift swiftui

来自 React 背景,如果定义了值,则很容易仅呈现视图。它看起来像这样:

function Component ({ profile }) {
  return (
    <div>{profile && <div>{profile.name}}</div>
  )
}
Run Code Online (Sandbox Code Playgroud)

但我发现在 SwiftUI 中复制这种模式要困难得多。理想情况下,我们可以在我们的视图中使用条件展开,但这目前不起作用。我能想出的唯一解决方案真的很不优雅:

function Component ({ profile }) {
  return (
    <div>{profile && <div>{profile.name}}</div>
  )
}
Run Code Online (Sandbox Code Playgroud)

有没有人有一些更好的策略来使用可选值进行条件渲染?

Lud*_*dry 7

您可以反过来使用map来处理可选的,如下所示:

struct ProfileView : View {
    var profile: Profile?

    var body : some View {
        profile.map { Text("profile: \($0.bio)") }
    }
}
Run Code Online (Sandbox Code Playgroud)

(在这个例子中$0是你解开的profile。)

如果您需要 else 情况:

profile.map { Text($0.bio) } ?? Text("Not available")
Run Code Online (Sandbox Code Playgroud)


ben*_*nto 1

只需这样做:

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

    // fetch method 
}
Run Code Online (Sandbox Code Playgroud)

  • 似乎与原来的问题没有密切关系。 (3认同)