Better Programming

Advice for programmers.

Follow publication

Member-only story

SwiftUI Binding Extensions

Michael Long
Better Programming
Published in
7 min readNov 19, 2022

--

Photo by Sigmund on Unsplash

Here are a few common SwiftUI issues that fall into the “there has to be a better way” category.

Optional Values

Let’s begin with optionals. It’s common to have optional values in our code due to API requirements, but working with them in SwiftUI can be a bit of a pain. Consider.

class SomeViewModel: ObservableObject {
@Published var name: String?
}

struct SomeView: View {
@StateObject var viewModel = SomeViewModel()
var body: some View{
TextField("Name", text: $viewModel.name) // does not compile
}
}

Here we have a view model with an optional name string and we want to be able to edit that value. Unfortunately, there’s no optional initializer for a TextField binding and the Swift compiler will give us an error. “Cannot convert value of type ‘Binding<String?>’ to expected argument type ‘Binding<String>’”.

What to do? I mean, if it was a Text view we’d just use a nil coalescing operator to provide a default value for the string in question.

But how do we provide a default value for a binding?

Binding Extensions

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Write a response