TL;DR: Animations can be built by interpolating your types.
We love Swift. And we use Swift not only for the sake of Swift.
It also enables us to write our applications in a safer manner. Plus it gives us concepts to empower reusable code parts.
Ultimately we can spend more time on thinking about our apps, than on writing code.
Watch out, for the concepts ⚒
So let’s apply some Swift concepts to build a cool feature for the watch.
When we did the first watch app we chose a data driven app. Knowing that the capabilities are constrained and not yet having the hardware was an interesting situation. The watch should display the data in bar diagrams. When you open the app - the diagrams should perform a transition to the new state.
Therefore you need to build a list of images with the intermediate states.
The hard facts:
You start with empty screen, empty horizontal bar.
After fetching data we get 3 BarSegments with different colors and width. The change is animated.
Maybe next time you receive 4 BarSegments, where the previous ones have a different width and maybe color. And the change is animated. So far so easy.
To gif you an idea:
We start like a california roll - inside-out. The key concept here is a protocol called Interpolation.
Every type conforming to this protocol can be interpolated, between a start and an end.
Next we wrap it in struct.
The idea is pretty easy and you should get the whole idea when looking at the following example, which is using custom operators.
Building up from the base types, we can make the BarSegment conform to Interpolation.
You will find all implementations on the end in the gist.
Zip like a pro 🤐
In order to get a consistent list of bar segments at the beginning and the end of the transition we need to ensure that both lists have the same number of bar segments.
We zip those lists with a custom generator. It gives us the possibility to fill up the missing elements, without doing it manually.
Watch on, for the animation ⌚️
First we need to zip the BarSegments, conforming to ImplicitDefault.
Next we map the list of tuples into Interpolations.
Then we stride over the values from 1 to 100 and build up the related list of BarSegments.
Each one interpolated at this point.
All we need is some easy cheesy drawing methods and the actual example is pretty much done: