Swift 3.0: Private vs. Fileprivate

Felicity Johnson
2 min readJan 12, 2017

--

Private

According to Apple’s documentation, “Private access restricts the use of an entity to the enclosing declaration.” Private access is the most restrictive access level. Basically this just means that you are not able to access the private type/func/property outside of the scope in which the private entity was defined.

In the example below, since var visibleButton and func getAge() were both defined within the PrivatePerson class, we are able to access those funcs within the entire scope of the PrivatePerson class. However, we are NOT able to access those entities within the PrivatePerson extension since the extension is NOT within the scope of the class in which the private entities were defined.

Given what you know from above, can you explain why I made the handleTapGesture func private?

Since the handleTapGesture func is a helper method and will only be called on by the configButtons() func in the extension, I decided to limit the access of the func solely to the extension. If I tried to call on the handleTapGesture func within the class’s definition, I would receive an “inaccessible due to ‘private’ protection level” error.

Fileprivate

According to Apple’s documentation, “Fileprivate access restricts the use of an entity to its own defining source file.” If you are familiar with Swift 2.0, fileprivate is the equivalent of Swift 2.0’s private.

The main difference between fileprivate and private is evidenced below. Fileprivate entities can be accessed within the entire file. In the example below, even though var invisibleButton and getName() were defined in the FileprivatePerson class, we can still access them within the FileprivatePerson extension.

You might be wondering why you have never had to define an entity as private/fileprivate and you have never received any warnings. This is because Swift defaults to “internal,” meaning the entity (type/func/property etc.) is accessible to the entire app/framework that includes the entity’s definition. Defining an entity as private/fileprivate is just going one step further in terms of your thoughtfulness about the code you are writing. Happy coding! 🤓

--

--