In the past few weeks I’ve had a lot free time, and thought to myself why not another Covid-19 app? Only for Canada. You can get it from here https://github.com/maysamsh/Swift-Covid19-Canada
I tried to practice having a clean, readable and modular code. I hope I achieved these goals. Three external libraries are used in the app. CSV to decode CSV data, Charts and MBProgressHUB to show an activity indicator (I really could avoid this one and use the native one).
Data which feeds the app comes from canada.ca website. The main challenge here was the input data were not consistent. From the URL to data structure. I fix the first problem I added a helper function to retrieve the file URL from an alternative when the primary function fails to fetch the file, you can getAlternativeAddress()
from DeliveryManager
class. To overcome to the data structure inconsistency I declared most of the columns as optional string and through two failable initializers converted them to Int
and Double
.
Another thing I practiced was using custom UIViews
, it is a good way to modularize the code and avoid having fat view controllers.
KeyPath
was another thing I used here. I guess most of us don’t care to use them, but they are really cool. Imagine you have a structure which consists of several Int
type and you want to manipulate some of the numbers and show different output for different purpose. In my case I wanted to feed the chart with two different set of data, one for confirmed cases and one for number of deaths. I could create two almost identical functions to generate required data or one generic function which knew what element of the structure should be used. KeyPath
was the silver bullet here:
func setChartData(data: [CSVDecodable], keyPath: KeyPath<CSVDecodable, Int>){}
Now I can call it like setChartData(data: data, keyPath: \.confirmed)
or setChartData(data: data, keyPath: \.deaths)
and it knows how to generate the data set.
You can download the project from https://github.com/maysamsh/Swift-Covid19-Canada