Access Control main purpose is to prevent the access of code in other modules or files. By access control code accessibility can be handle. By using Access control we can assign the specific access level to the class, structure, enumerations, properties, subscripts, methods, initializers.
Types of Access control:-
- Open
- Public
- internal
- fileprivate
- private
1) Open:- It has the highest access level means it is the least restrictive. It provides access levels from other modules and files.
2) Public:-It is almost similar to open but unlike open which is subclassed and override from other modules. By using the public we can not subclassed and override from defining modules.
Let takes an example to differentiate between Open and Public.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Module A open func bird(){ // some code } public func mammals(){ // some code } // Module B override func bird(){} // It will works override func mammal(){} // It gives error |
3) internal:- It is default access control. The method or class which declares internal can be accessed from anywhere within the same module.
For Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Module A class Test{ internal var amount: Double var tax: Double init() } //Module B Class Test2: Test{ let testObj = Test() testObj.amount = 90 // Gives erroe testObj.tax = 10 // it will works } |
4) filePrivate:- The fileprivate gives accessibility within one single swift file.
For Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
//Test.swift import UIKit class Test: UIViewController{ fileprivate var amount: Double? override func viewDidLoad() { super.viewDidLoad() } } //Test2.swift import UIKit class Test2: UIViewController{ override func viewDidLoad() { super.viewDidLoad() let testObj = Test() test.amount = 90.5 // will give error } } |
5) private:- It has the lowest access level means it is the highest restrictive. It restricts the entity to the enclosing declaration. According to swift doc “Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.”
For example
1 2 3 4 5 |
class Test{ private var amount = 90.5 } Test().amount // it will gives error |
Thanks for reading the blog.
You can also check other blogs from here. if you have any issue or suggestion you can leave your query/suggestion in the comment section.