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!


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)


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 ๐Ÿ˜Š

Swift Snippets ๐Ÿš€

Itโ€™s an initiative to share snippets that leverages theโ€ฆ

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and youโ€™ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer โ€” welcome home. Itโ€™s easy and free to post your thinking on any topic. Write on Medium

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