Practical use of key paths in MVVM

Arie Peretz
2 min readJan 23, 2021

Converting the data model into a presentable model is easy now.

Required familiarity

Motivation

When implementing MVVM architecture it’s likely that you have a data model that you would have to do some extra work on it in order to present it on the view.

There are many approaches for dealing with data formatting and the one I prefer the most is handling it on the model side.

Let me show you how I took advantage of the new Swift language feature in Swift 5.2 that was introduced in this Swift Evolution Proposal SE-0249.

Walkthrough

NOTE: Use Swift Playgrounds if you want to keep up.

In order to keep things simple here, let’s create a class that will mock our user details as if it were fetched from a server like this:

This fetchUser function returns us a UserResponseModel that is defined like this:

Assuming that we want to use this data to display a short sentence that describes our user, we should format the data in that way.

Let’s create a data model class for our view model to use:

The goal here is to take the response model and turn it into the data model we want. We can achieve this by implementing an extension on the response model using a computed variable like this:

Putting that struct-to-struct mapping as a computed variable gives us the opportunity to utilize it when mapping the response directly from our repository like this:

Here we use the power of key paths when using map operation on a publisher.

Pretty sweet! 😎

In conclusion

In many cases when dealing with server response data models we need to do some extra work on the data to be fit for display.

Extending the response data model with a computed variable makes it easy to arrange our code in one place and have it ready to use by the view model.

Finally, using this computed variable in a publisher’s map operation (through key path) is extremely easy and increases code readability.

Hope you enjoyed reading.

Happy coding!

Clap multiple times if you liked my article.

--

--