https://medium.com/@abhimuralidharan/swift-3-0-1-access-control-9e71d641a56c
We have open, public, internal, fileprivate, and private for access control.
If you use 'private' you can not use the(function or variable) property in other module. If you use 'open' you can use the property in other module and you can override it. If you use 'public' you can use this property other module but can not override it.
Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level.
Default access leve:
Almost all entities in your code have a default access level of internal if you do not specify an explicit access level yourself.
As a result, in many cases you do not need to specify an explicit access level in your code.
1) Open :
Ex: UIKit . UIKit has UIButton, UITableView etc...
We can access all UITableView properties
Ex: @available(iOS 2.0, *)
open class UITableView : UIScrollView, NSCoding { }
2)Public:
open access level allows us to subclass it from another module where in public access level, we can only subclass or overridde it from within the module it is defined.public func A(){}
open func B(){}
//module 2
override func A(){} // error
override func B(){} // success
3) internal (default access level):
internal is the default access level. Internal classes and members can be accessed anywhere within the same module(target) they are defined.
4) fileprivate:
Ex: // A.swiftfileprivate func someFunction() {
print("I will only be called from inside A.swift file")
}
// viewcontroller.swift
override func viewDidLoad() {
super.viewDidLoad()
let obj = A()
A.someFunction() // error
}
Ex: // A.swift
class A {
private var name = "First Letter"
}
extension A {
func printName(){
print(name) // you may access it here from swift 4. Swift 3 will throw error.
}
}
A()
A().name // Error even if accessed from outside the class A{} of A.swift file.
Interview questions:
1) What is the difference between public and open?
No comments:
Post a Comment