Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwrapping optional in SwiftUI View

Tags:

swift

swiftui

I try to unwrap my optional property, but get this Error message:

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)
like image 703
seref Avatar asked Oct 13 '19 22:10

seref


2 Answers

Swift 5.3 - Xcode 12

Using conditional binding in a ViewBuilder is perfectly fine now:

HStack {
    if let height = profile.height { // <- This works now in Xcode 12
        TagBox(field: "height", value: String(height))
    }
    TagBox(field: "nationality", value: profile.nationality)
    Spacer()
}.padding(.horizontal)
like image 169
Mojtaba Hosseini Avatar answered Oct 01 '22 03:10

Mojtaba Hosseini


There are two ways to work with optionals in this context:

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))
like image 36
LuLuGaGa Avatar answered Oct 01 '22 03:10

LuLuGaGa