Friday, September 14, 2018

fileprivate to private


In Swift 3, If we need to access private stuff of a class in extension, we need to change the access specifier from private to fileprivate.


     
  class User {
    
    private var name: String
    private var id: Int
    
    init(name: String, id: Int) {
        self.name = name
        self.id = id
    }
    
    private var greeting: String {
        get {
            return "Hi \(name)"
        }
        set(v) {
            name = v
        }
    }
    
 }

 extension User {
    func greetUser() {
        print(greeting)
    }
 } 



Swift 3 gives build error for below as greeting is private. 



     
  extension User {
    func greetUser() {
        print(greeting)
    }
  }



It should be marked as fileprivate which makes it accessible to others which are inside a file which may not be we wanted most of the times.

Swift 4, makes it appropriate based on their name.

private is not at all accessible outside even with in the same file.

fileprivate is accessible only with in the file, Not accessible outside of a file.

If greeting is with in the same file where User class is there, It doesn’t matter If it’s fileprivate or private to access it in a User extension with in the same file. But, careful with fileprivate cause it is accessible with in the same file. 


     
  class User {
    
    private var name: String
    private var id: Int
    
    init(name: String, id: Int) {
        self.name = name
        self.id = id
    }
    
    fileprivate var greeting: String {
        get {
            return "Hi \(name)"
        }
        set(v) {
            name = v
        }
    }
    
 }

 extension User {
    func greetUser() {
        print(greeting)
    }
 }



If you are writing extension of User in another file, You can not access it If it’s fileprivate or private.

Extension outside of file,


     
  extension User {
    func greetUser() {
        print(greeting)
    }
  }



fileprivate build error - 'greeting' is inaccessible due to 'fileprivate' protection level

private build error - 'greeting' is inaccessible due to 'private' protection level


That’s how Swift 4, make both the access specifiers clear based on their name. 

Glad, It’s not confusing now like in Swift 3.

Swift 3, fileprivate -  If you need access throughout the file even in extensions (private gives build error in extensions)

Swift 3, private - Not accessible outside the model scope even in the extension which is there in same file.

Swift 4, fileprivate - If you need access throughout the file.

Swift 4, private - Accessible in extensions If they are in the same file. Not accessible for all remaining cases.

Take Aways - 

In Swift 4, We don’t need to change fileprivate access for a property/method to private to access that in the extension in the same file.


Hope this post is useful. Feel free to comment incase of any queries.