Swift 3: Private & Fileprivate explained

Apple has released swift 3 and many developers are having nightmares, as older code would refuse to build in Xcode8 until the necessary changes are made. This could mean a lot of sleepless nights and late working hours for some days. While there are a lot of them who are totally relaxed throughout.

I will be writing about the swift updates in the upcoming posts, for this one I am talking a smaller section. Swift 3 has brought many major changes and one of them is the introduction of a new Access Modifier: Fileprivate.

Fileprivate is now what private used to be in earlier swift versions. you can very well guess from the name itself, private on a class level. Whatever the functions, variables are defined using Fileprivate will be accessible only in that class in all the scope.

Whereas , the private modifier is more restrictive than Fileprivate. All the declarations with private can only be accessed within the lexical scope(where it is declared). For example, if declared a class variable with Fileprivate modifier, then it can be used in all the extensions in that source file, where is using private would give an error, as it was declared in a class scope and now being used in. I will demonstrate using an example for table views.

Step 1: Create a new view controller file , and two class level ivars, both String array, one with private modifier & other with FilePrivate.

Step 2: Make an extension for the class,conforming to UITableViewDataSource protocol, and implement the two tableview data source functions, numberOfRowsInSection() , & cellForRowAtIndexPath().

Step 3: in numberOfRowsInSection(), first return the fileprivate array count. Everything will be fine , and code will compile successfully. now try to return private array count, you would not even see that variable in Code sense auto-completion. Even if you manually wrote, compiler would give an error. Since because you declared private variable in class scope, you cannot use it in the extensions ,as they are different scope.

As a rule of thumb, private for variables, constants, inner structs and classes that are used only inside the declaration of your class / struct. When you want a variable to be accessed in the whole file, use Fileprivate.

This was all for the first story, other new updates blogs coming soon.

Leave a Reply

Your email address will not be published. Required fields are marked *