SwiftUI - 带有条件闭包的 if let 的替代方案 [英] SwiftUI - alternative to if let with a conditional closure

查看:53
本文介绍了SwiftUI - 带有条件闭包的 if let 的替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 SwiftUI 中实现以下内容:

I'm trying to implement the following in SwiftUI:

struct PersonView: View {

    @State private var age: Int? = 0

    var body: some View {
        VStack {
            Text("Just a test")
            if let self.age > 0 {
                Text("Display Age: \(age)")
            } else {
                Text("Age must be greater than 0!")
            }
        }
    }
}

但是,在 SwiftUI 中,if let 会导致以下错误:

But, in SwiftUI, if let results in the following error:

包含控制流语句的闭包不能与函数构建器ViewBuilder"一起使用

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

所以在研究了这个话题之后,我遇到了使用 .map 来解包 age 可选的建议.因此,我修改了 VStack 中的代码,如下所示:

So after researching this topic, I came across a recommendation to use .map to unwrap the age optional. Thus, I've modified to code within the VStack as follows:

Text("Just a test")
self.age.map {elem in
    if elem > 0 {
        Text("Display Age: \(elem)")
    } else {
        Text("Age must be greater than 0!")
    }
}

.map 闭包中包含条件,但是会导致调用 VStack 的行出现以下错误:

Including a conditional within the .map closure, however, results in the following errors at the line calling the VStack:

' (ViewBuilder.Type) -> (C0, C1) -> TupleView<(C0, C1)>' 要求'()'符合'View'

' (ViewBuilder.Type) -> (C0, C1) -> TupleView<(C0, C1)>' requires that '()' conform to 'View'

类型 '()' 不符合协议 'View'

Type '()' does not conform to protocol 'View'

关于如何克服第二组错误的任何建议?或者,是否有另一种方法可以在 SwiftUI 中解开可选项并评估它们?真的很喜欢 SwiftUI,但不敢相信解包选项是一件令人头疼的事!

Any suggestions for how to get past the 2nd set of errors? Or, is there another approach for unwrapping optionals and evaluating them in SwiftUI? Really like SwiftUI but can't believe that unwrapping optionals has been a headache!

推荐答案

对于这种情况我更喜欢下面的方法

For such cases I prefer the following approach

struct PersonView: View {

    @State private var age: Int? = 0

    var body: some View {
        VStack {
            Text("Just a test")
            AgeText
        }
    }

    private var AgeText: some View {
        if let age = self.age, age > 0 {
            return Text("Display Age: \(age)")
        } else {
            return Text("Age must be greater than 0!")
        }
    }
}

这篇关于SwiftUI - 带有条件闭包的 if let 的替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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