Optionals in SwiftUI

Apple’s new UI framework is missing an “if let”, so now what?

Jasper Haggenburg
Jun 6 · 3 min read

Working with optionals

One of the things you’ll encounter a lot when building UIs is optional values. You get data from an API and need to render some UI accordingly, but you can’t assume all data is available. Taking a Twitter app as an example, you’d guess you can do something like this:

Function builders

Welcome to the world of Function Builders! This is a new feature in Swift, you can read its proposal if you’re interested. Function builders provide us with a way of collecting the result of functions into an output. SwiftUI uses this to get the output of your components and turn it into a UI (it’s called the ViewBuilder). All SwiftUI views (like Group, HStack, List and so on) are ViewBuilder's. Because of this, the code you type inside of a view isn’t “just Swift”, it’s “Swift that is supported from within the function builders that Apple has provided in this version of the framework”.

Update: Use map instead!

After fiddling around with this a little bit more, we found another way of doing this:


Q42 Engineering

Pragmatic code—happy users

Jasper Haggenburg

Written by

Developer, working at @Q42. Also loving movies, music, cities, weird people and more.

Q42 Engineering

Pragmatic code—happy users