Swift 4— Access Control

Access control restricts access to parts of your code from code in other source files and modules. This feature enables you to hide the implementation details of your code, and to specify a preferred interface through which that code can be accessed and used.
You can assign specific access levels to individual types (classes, structures, and enumerations), as well as to properties, methods, initializers, and subscripts belonging to those types. Protocols can be restricted to a certain context, as can global constants, variables, and functions.
In Swift 3 and swift 4, we have openpublicinternalfileprivate, and private for access control.Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level.
As of Swift 4, there are 5 levels of access, described below from the highest (least restrictive) to the lowest (most restrictive).

1. open and public — (least restrictive)

Enable an entity to be used outside the defining module (target). You typically use open or public access when specifying the public interface to a framework.
Let’s consider an example. Everybody (iOS developers) knows about UIKit. We often use many UI elements from UIKit daily. When you try to use the UIComponents such as UIButton, UICollectionView, UITableView, UIViewController etc.., you have to import the UIKit on the top. So UIKit is actually a module that we can import to our class and subclass its features.
@available(iOS 2.0, *)
open class UITableView : UIScrollView, NSCoding { }
Since it is open, we can subclass it from our ViewController and use it.
tableView: UITableView() {} // some another module

2. Public

Like open access level, public access level enable an entity to be used outside the defining module (target). But 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. Look at the following example.
//module 1
public func A(){}
open func B(){}
//module 2
override func A(){} // error
override func B(){} // success
Method A declared in module 1 as a public method cannot be accessed from module 2.It gives error . But Method B declared in module 1 as an open method can be accessed from module 2.
So by keeping it simple, open access applies only to classes and class members, and it differs from publicaccess as follows:
  • public classes and class members can only be subclassed and overridden within the defining module (target).
  • open classes and class members can be subclassed and overridden both within and outside the defining module (target).
Open access applies only to classes and class members, and it differs from public access as follows:
  • Classes with public access, or any more restrictive access level, can be subclassed only within the module where they’re defined.
  • Class members with public access, or any more restrictive access level, can be overridden by subclasses only within the module where they’re defined.
  • Open classes can be subclassed within the module where they’re defined, and within any module that imports the module where they’re defined.
  • Open class members can be overridden by subclasses within the module where they’re defined, and within any module that imports the module where they’re defined.
Marking a class as open explicitly indicates that you’ve considered the impact of code from other modules using that class as a superclass, and that you’ve designed your class’s code accordingly.

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. You typically use internalaccess when defining an app’s or a framework’s internal structure.
Lets consider another example from UIKit to explain this. Suppose there is an internal method declared inside the UIKit module. Let’s say a method called internalMethod() .
internal func internalMethod() {
 print("I am inside UIKit")
}
Even if we import UIKit, we cannot use the internalMethod() inside our ViewController. It can only be accessed anywhere within the same module of UIKit.

4. fileprivate

Restricts the use of an entity to its defining source file. You typically use fileprivate access to hide the implementation details of a specific piece of functionality when those details are used within an entire file. ie; the functionality defined with a fileprivate access level can only be accessed from within the swift file where it is defined.
// A.swift
fileprivate 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
}

5. private — (most restrictive)

Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. You typically use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
// 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.

Important: Before swift 4, private access level didn’t allow the use of a class member inside the extension of same class.

Interview questions:

1. What is the difference between public and open?

Entities that are declared public or open are accessible from the module in which they are defined and from any module that imports the module they are defined in. The open access level was introduced to impose limitations on class inheritance in Swift.Open access level can only be applied to classes and class members, such as properties and methods.
  • An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
  • public class is accessible but not subclassable outside of the defining module. A publicclass member is accessible but not overridable outside of the defining module.
Keeping it short, Both public and open comes to play only between modules. Internal access mode will give public access throughout the same module.
Ex: If you are creating a framework for facebook login in swift. The developer will import the framework you created and try to call the login() function. if you want the developer to call this method, it should be declared as publicinside the framework. If you want the developer to call the function and override the login() function, it should be declared as open. Simple!!
2. What is the default access level in swift?
It is Internal . If we don’t mention an access level before any variable, constant or function, it is Internal by default. It’s explained in the above section.
Thats it! enjoy …Happy coding..!

Comments

  1. Such an ideal piece of blog. It’s quite interesting to read content like this. I appreciate your blogiOS Online Training

    ReplyDelete
  2. I am really impressed with your blog article, such great & useful knowledge you mentioned here.

    Hire Affordable Xamarin Developer
    Xamarin Developers in Frisco

    ReplyDelete
  3. What a great online source of information about this topic. You have done great work... Keep it up !!!

    If you want to make custom website & application you can contact us on our iOS App Development Company and PHP Web Development Company anytime.

    ReplyDelete
  4. It is a very informative and useful post thanks it is good material to read this post increases my knowledge. Drive store visits

    ReplyDelete
  5. I am extremely pleased to uncover this blog. I need to to thank you for one time, just for this wonderful read. Mobile App Development Company jaipur

    ReplyDelete
  6. Thank you for sharing new upadtes about swift.
    keep sharing more new updates.

    ios online training

    ReplyDelete
  7. U3.NET is a cloud studio that enables any business owners to build and manage their own mobile app in an easy and affordable manner, with no technical knowledge required and the ability to update the content and features any time the need arise with U3 you can create a full-fledged mobile application in 3 easy steps (Design, Build, publish) with an array of Value-Adding Features
    Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
    will help you more:
    Create Mobile App For iPhone And Android Without Coding

    ReplyDelete
  8. This is a very interesting web page and I have enjoyed reading many of the articles and posts contained on the website, keep up the good work and hope to read some more interesting content in the future. App Developers Toronto, Medical App Development companies

    ReplyDelete
  9. It's really a valuable blog post. This blog briefly explains about Swift 4. Swift is one of the prominent programming languages mostly used while the process of developing iPhone Apps. Thanks for sharing this nice article.

    Looking for a iPhone App Development Company in UK? Reach Way2Smile Solutions UK.

    ReplyDelete
  10. This is such an extraordinary asset that you are giving and you it away to free. I love seeing web journal that comprehend the worth.

    iOS Application Development Company

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Really a nice blog. Thanks for sharing this one. I love this topic very much.

    iPhone Software Development Company in Chennai

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. I am more thankful for you to sharing this great blog with us.
    Importance of Data Science
    Benefits of Data Science

    ReplyDelete

Post a Comment

Popular posts from this blog

iOS Architecture

Property vs Instance Variable (iVar) in Objective-c [Small Concept but Great Understanding..]

setNeedsLayout vs layoutIfNeeded Explained