Swift 5- Open, Public | internal | Fileprivate | private in Swift: The differences explained by Divesh Singh
Note :
- Open and public comes to picture when we are talking about different target/module.
- Internal, FilePrivate and private is used within Target/module
Open : This Access level is everywhere, can access within function, within class, within file, outside of target and even can override as well
Public : Same as open but can not override.
Internal : This is default access level. It can be access within module everywhere.
FilePrivate — This access level area is within file if multiple classes exits in the same file, that also can be accessible.
Example 1: fileprivate variable is accessible within file after inheritance. See below image.
Example 2 : FilePrivate member can not access from another file. see image
private — access within body where you have written private, However Attribute ‘private’ can only be used in a non-local scope and private member is accessible with extension as well but in the same file.
Private Example: Suppose we have created one class with one Private variable, this variable can not be accessible by the other class as this is private it can be access with in class body { }. See the below image where we can not user private attribute in local scope.
Private behaviour with extension in the same file and in different file:
After extension, you can access private member within file only.
For example A.Swift file has customer class with private member.
A.swift
class Customer: UIViewController {
private var acno : Double = 123
}
And now I am going to extend Customer class in the same file and this is allowed to use.
extension Customer {
func accesprivateMember() {
print(acno)// Correct sentence
}
}
But at the same time if I extend same class in different B.swift file it will give error
B.swift
extension Customer {
func accesprivateMember() {
print(acno)// Error will generate
}
}
- In Protocol oriented programming lazy member not allowed.
2. Extensions must not contain stored properties
3. open, public, internal, fileprivate, private modifier cannot be used in protocols.
I hope this article can help you clear up the difference among all access level: Open, Public | internal | Fileprivate | private
Please do not hesitate to hit the 👏 button or share this article if you like it. If you have any comments or questions, just drop it in the comment section below.
Feel free to follow me on Medium if you want to read more article like this in the future.