Since I wrote the table view data source code in Part 8, I have experimented with table views and table view cells a lot. And I found a way of setting the data in the cell that I like more now. Most probably that will change in the future. That is the point of being a developer. Code I write today will probably scare me in half a year. I fear the day when this stops. Change of preferences is a good thing. Without it I’d have stopped improving.
Before we improve the setting of the cell data, let’s first improve the
The method has a few problems. First, the return type is optional. What
does a nil progress mean? It would be nil, if
would be nil. That should not happen. We set
didSet of the
property. And that is set in
A better version would look like this:
Much better. Here we use guard to unwrap the
if this unexpectedly fails, we return a progress on
0.0. In this case,
the user would just see the info in the cell without the progress. That
would result in the same behavior as the version before.
Now let us improve the setting of the data to be shown in the cell.
The compiler complains the
have a method
Let’s change that. Add the following code to BirthdayCell:
This makes the cell responsible to update its UI. I find this pattern much better than letting the controller or the data provider update the label and the progress. But keep in mind that with this change, the view and the model are more coupled than they have been before. The cell now knows that there is something like a birthday. But it already knew that in some way. The UI was designed to show the information of a birthday instance.
If you have difficulties to accept that design, you can add a protocol
Birthday conform to
Another thing to note is, we have implemented
as a generic method. But in this case this doesn’t help much. We could
have used the type
Sure there is still code that could be improved. But that has to wait for some of the next posts in this series. Stay tuned.
As always, find the code at github.