So that’s the basics of building a moderately complex settings. We are leveraging the power of SwiftUI and the Form
view to get a ton done for us basically for free. It’s super easy to get a form up on the screen, and easy for changes to that form to be instantly reflected in a backing model.
However, we did uncover a few complexities that arise when dealing with something a little bit more realistic, and not just a simple demo. For one thing, we saw that if we need to react to a change in the model, such as wanting to truncate the display name to be at most 16 characters, then we had to tap into the didSet
of that field. However, it is very dangerous to make mutations in a didSet
. As we saw it can lead to infinite loops, and it can be very difficult to understand all the code paths that can lead to an infinite loop. It’s possible for the didSet
to call a method, which calls another method, which then mutates the property, and then bam… you’ve got an infinite loop on your hands.
Another complexity is that if you want to do something a little more complicated when the form changes, such as hook into notification permissions, then you are forced to leave the nice confines of ergonomic magic that SwiftUI provides for us. We needed to write a binding from scratch just so that we could call out to a view model method instead of mutating the model directly. Doing that wasn’t terrible, we just think it’s worth pointing out that working with more real world, complex examples you often can’t take advantage of SwiftUI’s nice features, and gotta get your hands dirty.