Access modifiers are the identifiers which let us control the access level of class/struct/variable or methods.
In swift there are following Access Modifiers -
1. internal - This is the default one. When don't mention any then this is the default type of access the class/struct etc get.
In this one entities can be access and inherited within the target.
Access level - accessible & inheritable within target
2. private - With this one entities are only accessible within class scope and, when accessed out of class then will give error.
Access level - within enclosing declaration
Example - In below screenshot , the property osName
is inaccessible due to private access.
3. fileprivate - Just as the name explains, the entities are accessible within enclosing declaration and within same file i.e in which it is declared.
Access level - within enclosing declaration & within same file
Example 1 - In below screenshot, the property osName
is accessible out of its class scope because those classes are created in same file.
Example 2 - In below screenshot, the property osName
is inaccessible because the class accessing it is not in the same file in which osName was created. Hence, causes error.
4. public - This makes the entity accessible among other targets also however, they can't be inherited in the other targets.
Access level - accessible in other targets but not inheritable out of self target
_Example 1 - _
Target 1 -> class ViewController
Target 2 > class NRDropDownHelper
NRDropDownHelper is inaccessible in Target 1 (ViewController
class) due to it's default internal level. Hence, causes error.
_Example 2 - _
After changing the class access to public
- It becomes accessible in ViewController
- Yet can't be inherited outside target hence causes error.
5. open - This is the highest level of access in swift. With this entities are accessible and inheritable in outside target as well.
Access level - accessible and inheritable in other targets as well
example class NRDropDownHelper
is access and is also inherited in class customHelper
.
Top comments (0)