1 year ago

#144706

test-img

Vincent F

Handling Optional Values in SwiftUI Text View: Best Practices?

I've often found myself in a situation where I have optional data (such as optional properties coming back from an API) that I want to display in a SwiftUI View if they exist, and skip over if they are nil.

Recently, a senior developer told me I should not have conditional logic in my swiftUI views. I used to check optionality on properties in my ViewModel within the View using if let. Now I'm wondering if there is a better way?

Based on this answer I can see there are a few different ways to do this.

  1. if property != nil { Text(property!) }
  2. if let unwrappedProperty = property { Text(unwrappedProperty)
  3. property.map { Text($0) }
  4. Handling the optional property in a helper function that wraps the result in AnyView()

private func optionalView(_ property: property)
{
   if let unwrappedProperty = property {
       return AnyView(Text(unwrappedProperty) })
   } else {
       return AnyView(EmptyView())
   }
}
  1. Provide a default value using Text(property ?? "") (this one is different from the rest as this will create a Text View with an empty string, whereas the others will not create the view at all.

So all of these options work, and I was curious Which is preferred?

First, I wanted to check the performance of each option, so I created a load test based on this great article.

What I found was that all the options render at the same performance, except for option five which renders about 7% faster. This makes sense to me as in option #5 the TextView is always being rendered and my test isn't about state changes, just optionality. I wouldn't use that option in the real world because as your model increases in size you'd have to hard code hundreds of default values.

So if the performance from options 1-4 is the same, which is preferred?

My inclination is to believe that #3 property.map { Text($0) } is the cleanest and most clear option so that is what I have been using.

However, I'm also wondering if perhaps I'm missing a bigger paradigm issue; Should I never be observing optional properties in my view at all?

If your API has the potential to return null values for properties, should I have an interface that manages that before reaching the ViewModel? I'm not sure how I would handle that.

My end goal is to have a modular view that is able to handle a dataset with various missing pieces of data and leave those out of the View Hierarchy.

ios

swift

swiftui

option-type

instruments

0 Answers

Your Answer

Accepted video resources