Swift 4 / Swift 5

As per mentioned in the Swift Documentation - Access Control, Swift has 5 Access Controls:

open and public : can be accessed from their module's entities and any module's entities that imports the defining module.

internal : can only be accessed from their module's entities. It is the default access level.

fileprivate and private: can only be accessed in limited within a limited scope where you define them.





What is the difference between open and public?

open is the same as public in previous versions of Swift, they allow classes from other modules to use and inherit them, i.e: they can be subclassed from other modules. Also, they allow members from other modules to use and override them. The same logic goes for their modules.

public allow classes from other module to use them, but not to inherit them, i.e: they cannot be subclassed from other modules. Also, they allow members from other modules to use them, but NOT to override them. For their modules, they have the same open's logic (they allow classes to use and inherit them; They allow members to use and override them).





What is the difference between fileprivate and private?

fileprivate can be accessed from the their entire files.

private can only be accessed from their single declaration and to extensions of that declaration that are in the same file; For instance:

// Declaring "A" class that has the two types of "private" and "fileprivate": class A { private var aPrivate: String? fileprivate var aFileprivate: String? func accessMySelf() { // this works fine self.aPrivate = "" self.aFileprivate = "" } } // Declaring "B" for checking the abiltiy of accessing "A" class: class B { func accessA() { // create an instance of "A" class let aObject = A() // Error! this is NOT accessable... aObject.aPrivate = "I CANNOT set a value for it!" // this works fine aObject.aFileprivate = "I CAN set a value for it!" } }





What are the differences between Swift 3 and Swift 4 Access Control?

As mentioned in the SE-0169 proposal, the only refinement has been added to Swift 4 is that the private access control scope has been expanded to be accessible from extensions of that declaration in the same file; For instance:

struct MyStruct { private let myMessage = "Hello World" } extension MyStruct { func printMyMessage() { print(myMessage) // In Swift 3, you will get a compile time error: // error: 'myMessage' is inaccessible due to 'private' protection level // In Swift 4 it should works fine! } }