Swift snippet #13 — Extension Oriented API

Tuesday, 3rd October, 2017

I posted my last swift snippet way back in March, so roughly it’s been 6 months now. I wanted to be more active, but a lot has happened since then. Now I’m rekindling this series of snippets and hopefully will continue posting for a longer time 🚀.
You can find its Gist here!

About

With this post, I would like to highlight the power & relevance of creating Extensions. In my recent app, I had to use FileManager api and it’s really easy to use them btw. But after using it at couple of places, I was calling the same functions again, FileManager.default.contents(atPath: path) or FileManager.default.someFunc(). I felt it could be refactored and thus got the idea of converting the same api into more extension-oriented rather than function-oriented where you have to pass the argument.

If you observe the api — FileManager.default.contents(atPath: path), it takes exactly one argument i.e. path and thus we can make an extension on this argument (URL in general) to achieve the same result. In this case, it adds two benefits. It makes the new api,

  • inline (you can get the same result by using dot notation)
  • shorter (makes it easier to read)

Usage

Let’s say we want to read the contents of a json file name "model_user". With the above extensions, now you can achieve something like this,

let userData = "model_user".fileURL.fileContent
  • fileURL gets the correct url of the file from the document's directory, eliminating the need to figure out how to get the document directory's url.
  • fileURL internally uses fileName which make sure that we have a centralised variable to do any processing on the file name so that the chances of getting it wrong reduces.
  • fileContent uses the FileManager api to get the required data

Thus the final api is dependent on smaller pieces of logic which are abstracted in the extension. If you want, you can make the api even shorter by using the below extension,

extension String {

var fileContent: Data? {
return fileURL.fileContent
}
}

let userData = "model_user".fileContent
Though I’m not saying shorter is better, it’s a matter of how much further you should/could go (clarity is more important than brevity) 🚀

If you are wondering about the inception of Swift-Snippets or want to checkout more such snippets, you can find them here 😊