Extensions, Private and Fileprivate
Encapsulation is one of the four fundamentals of Object Oriented Programming. Access control is part of the apparatus that enables encapsulation[1]. Private, Fileprivate, Internal and Open are the four access controls available for us in Swift.
This post is a short note on how i would use extensions along with private and fileprivate to organise my code, which leads to abstraction.
Abstraction at the beginning of the project is hard, especially when all the features and requirements of the product is not clear. This is where, how we organise our code comes very handy.
One of the things i have benefited from, is using extensions to organise my code. As the project evolves these extensions tend to become seperate classes, structs or protocols (mostly protocols in my case) and helps me to convey my intentions to other developers clearly.
Lets look at this example of a news app, which has two tabs of collection view each showing list of content of some type
TabA — Shows a list from some collection, but the requirements are not completly defined.
TabB — Shows recently added news articles, there will be a media indicator (Video or Audio) in the UICollectionViewCell based on the content embedded in the article. In this post, I am going to focus on the media indicator feature.
We know the requirements for TabB, for which one of the viewmodels called ArticleTeaser (Take 1) shown here. It has a title, a short synopsis of the article and the media embedded in the article. There is a computed property mediaDisplayType which show what type of media it is.

Now let’s look at the another example on how we organised the code with some extensions

Now this extension provides the ability to find the media type embedded from a list of media. This also makes it clear to other developers to use mediaThumbnailType fileprivate function, which is the interface for this extension.
One of my colleagues always ask me why do you have an extension with just only one function? The answer is that I tend to group the functions which provide a particular behaviour of a class/struct into an extension, even though it is just one function. This come in handy as the code base grows.
Now when the requirements of TabA arrived, we noticed it also has to display some information about the media type. If we notice the extension we have used functions with no side-effects, so we can easily move this into a protocol.


We can think of these extensions with fileprivate functions, much like any other interface we write but ALSO AS an interface for use within a single class/struct. Happy coding…
[1] https://en.wikipedia.org/wiki/Access_control#In_object-oriented_programming
