I finally got sometime to refactor the code of my App Leetcoder. The followings are a few things I deem worth writing down.
Code like the snippet below is not only ugly but also unresponsive: it blocks the user interface.
I have changed much of that into async requests a while back but I finally got the time to change all of that.
Now all my code uses Alamofire to fetch JSON data instead.
It may not seem necessary to some if the size of the data to be fetched is small or when there is nothing to do anyways before any data can be loaded. However, slow network happens and showing a loading screen is much more conforting than showing nothing at all.
Swift’s property observer is a great way to put code in the relevant place. You should use it if something needs to happen whenever a property changes.
For example, when you display an array of data in a tableview, you probably want to reload the table whenever the array changes. That’s super easy to accomplish with property observers in Swift.
The snippet below is a little unpleasant… It’s mainly because that to pass a string to NSURL, you need to encode it first. And the way to encode it involves two long names.
Luckily, you can hide this little detail by using an extension:
In this way, you will be able to just write
That’s much better, isn’t it?
extension in Swift a lot and have seen many neat usages in other people’s code. When used properly, it makes your code cleaner and much more readable.
A common theme in my app is waiting for data to be returned from network requests. I used NVActivityIndicatorView to display a nice loading screen but I configured an instance in each view controller that I needed it. Therefore, I got some unpleasant duplicate code in the project. Since the loading screen should be consistent across the entire app anyways, I can just use a singleton to do that.
In this way, If I want to change the look of the loading indicator, I can just configure it in a single class.