Swift snippet #13 — Extension Oriented API

Ritesh Gupta
Oct 3, 2017 · 2 min read

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!


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,


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

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 😊

Swift Snippets 🚀

It’s an initiative to share snippets that leverages the…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store