Write better SwiftUI code: Decomposing SwiftUI views.

Tejas M R
3 min readApr 6, 2021

If you are reading this article, chances are you have written SwiftUI code before. Managing Code Complexity and keeping your code clean is very important in both the Software Development process and Maintenance process. If what you have written before looks like this:

then you may not appreciate the simplicity and cleanliness of the code you will learn from now on.

On the other hand, if you have written more complicated and nested code, then you know how difficult it becomes to read and debug your code.

Usually, when we decompose a view in SwiftUI, we use more views to achieve that. For example:

Here, CardView is a SwiftUI view, which looks a bit messy. Some SwiftUI View we write are going to have hundreds of lines of code and will be way messier.

Usually programmers use “refractor to subview” to solve this problem. I believe this solution almost doesn’t solve the problem and also brings a lot of complexity when message passing from subview to parent view and vice versa. You would need to use lots of @Binding and @ObservableObject objects to pass data which are usually not necessary when you have that one super long and messy view.

Let me explain this to you with the above example:

This is what developers usually do and don’t get me wrong, this is way cleaner code than what we had before. This method increases the complexity of the code as the View becomes bigger and more data has to be sent to and fro.

But Swift and SwiftUI have so many more ways to refractor and I have found a better way.

The way is using more “some View”s. The above example can be decomposed like this:

As you can see, this is way better than what we had before.

But wait! Since you read this article too the end I have a way to make this even better, using the extension feature of the Swift Language. This is how that goes!

Thank you for reading! Be sure to follow me — Tejas M R, for more articles like this :)

--

--

Tejas M R

Tejas M R is a Junior iOS Developer who is also interested in Machine Learning, Data Science, Creative Writing, Cybersecurity and more!