如果变量不为零,如何在 swift UI 中显示文本视图? [英] How to display a text view in swift UI if the variable isn't nil?

查看:30
本文介绍了如果变量不为零,如何在 swift UI 中显示文本视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这基本上是我的代码:

var myString: String?

var body: some View {
  NavigationView {
    if myString != nil {
      CustomView(text: myString ?? "")
    }
  }
}

如果我尝试不添加 ??"" 部分,它不起作用,说 可选类型字符串?"的值必须解包为字符串"类型的值.如果我如上所示添加它,它似乎可以工作,但是如果永远不会出现这种情况,为什么我需要有一个默认的空字符串值?(因为它只会在 myString 不为 nil 时才到达该代码)有没有办法让这段代码更简洁?

If I try without adding the ?? "" part, it doesn't work, says Value of optional type 'String?' must be unwrapped to a value of type 'String'. If I add it in as shown above, it seems to work, but why do I need to have a default empty string value if that's never going to be the case? (Since it will only reach that code if myString is not nil) Is there a way I can make this code more cleaner?

推荐答案

您需要使用可选绑定来解开安全可选的变量.然而,在 body 中简单地使用它会导致编译器错误,因为并非所有控制流(包括 if let)都允许在 body视图,因此您需要将其包装在另一个计算属性中.

You need to use optional binding to unwrap the safely optional variable. However simply using that inside body will result in a compiler error because not all control flow (including if let) is allowed inside the body of the view, so you'll need to wrap it in another computed property.

struct MyView: View {

    var myString: String?

    var body: some View {
      NavigationView {
        innerView
      }
    }

    var innerView: some View {
        if let myString = myString {
            return AnyView(CustomView(text: myString))
        } else {
            return AnyView(EmptyView())
        }
    }
}

或者你可以使用 Optional.map 来简化它.

Or you can simplify that using Optional.map.

struct MyView: View {
    var myString: String?

    var body: some View {
      NavigationView {
        myString.map { CustomView(text: $0) }
      }
    }
}

这篇关于如果变量不为零,如何在 swift UI 中显示文本视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆