Access Controls
Access control restricts access to parts of your code from code in other source files and modules. Swift’s access control model is based on the concept of modules and source files.
Module: A module is a single unit of code distribution — a framework or application that is built and shipped as a single unit and that can be imported by another module with Swift’s import keyword.
Source file: means a file where you write code.
Example: ViewController.swift
open var view: UIView!public var view: UIView!internal var view: UIView!
or
var view: UIView!fileprivate var view: UIView!private var view: UIView!
Access controls in Swift
Open and public
Open access and public access enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module.
Then, what is the difference between OPEN and PUBLIC ?
Open access applies only to classes and class members, and it differs from public access by allowing code outside the module to subclass/inherit and override.
In UIKit- UIViewController class viewDidLoad() defined as
open func viewDidLoad() because of we can override this function and use in our class like
override func viewDidLoad() {
super.viewDidLoad()
}
In UIKit- UIViewController class declared as open class UIViewController.
because we inherit this as
class ViewController: UIViewController {}
Internal (default access control)
Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module.
File-private
File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.
Private
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
Difference between fileprivate and private?
We can access private entity anywhere in declared class, its extension if declared in same class only, not in other file.
we can accesss fileprivate variable anywhere in same source file, if that source file contain multiple classes we can access it in that class too but private variable is not accessible.
Private is more restrictive and Open is less restrictive.
Thank you, Happy coding!