SwiftUI: Hiding Text with an if statement if text value is nil or N/A

Viewed 922

I am trying to do something that was simple to me in UIKit - but cannot get working in SwiftUI.

I am pulling data from an API. That data is dynamic - some parts of the call may not be present every time. I have protected the app by making all of that data optional and using a nil operator to return "N/A" in the text fields where there is no data. In UIKit I was able to simple use an if statement:

if self.cityLabel.text == "N/A" {
    self.cityLabel.isHidden = true
}

Now in SwiftUI, I have the following:


HStack() {

     Text(self.model?.city ?? "N/A")
                            
}

When the data is present, it displays without any issue. However, I am not sure where to access this property or put an if statement because this data is in a View class and does not accept functions.

So basically, how do I hide that text and have the blocks around it "move up" (like display: none) in HTML while in SwiftUI? How can I implement if statements in the View code?

I'm sure it's probably simple, but assistance would be much appreciated! :)

1 Answers

if, if-let, and if-else now also work inside View (I think it's introduced in Xcode 12). This should work:

var body: some View {
    HStack() {
        if let city = self.model?.city {
            Text(city)
        }                      
    }
}

Edit: If you don't care about what's inside self.model?.city, just do a simple boolean test for nil.

var body: some View {
    HStack() {
        if self.model?.city != nil {
            /// self.model?.city is not nil!
            Text("Not nil")
        }                  
    }
}

Edit 2: Ok, so if the text is "N/A", you don't want to display it. However, because the text itself (self.model?.city) is an optional, you need to unwrap it first.

var body: some View {
    HStack() {
        if let city = self.model?.city { /// unwrap self.model?.city
            if city != "N/A" { /// city is not "N/A"!
                
                /// show the text
                Text(city)
            } /// else, don't show anything
        }               
    }
}
Related