在 SwiftUI 视图中解包可选 [英] Unwrapping optional in SwiftUI View
本文介绍了在 SwiftUI 视图中解包可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试解开我的可选属性,但收到此错误消息:
I try to unwrap my optional property, but get this Error message:
包含控制流语句的闭包不能与函数构建器ViewBuilder"一起使用
Closure containing control flow statement cannot be used with function builder 'ViewBuilder'
我看不出我的代码有什么问题
I don't see whats wrong with my code
HStack {
if let height = profile.height {
TagBox(field: "height", value: String(height))
}
TagBox(field: "nationality", value: profile.nationality)
Spacer()
}.padding(.horizontal)
推荐答案
在这种情况下,有两种方法可以使用可选项:
There are two ways to work with optionals in this context:
第一个,如果你不想在 profile.height 为零的情况下显示这个视图:
The first one, if you don't want this view to show at all if profile.height is nil:
profile.height.map({ TagBox(field: "height", value: String($0))})
第二个,如果你想显示这个视图,但使用默认值:
The second one, if you want this view to show, but with a default value instead:
TagBox(field: "height", value: String(profile.height ?? 0))
这篇关于在 SwiftUI 视图中解包可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文