DEV Community

NalineeR
NalineeR

Posted on

2

Swift Access Modifiers

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

Image description

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.

Image description

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.

Image description

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.

Image description

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

  1. It becomes accessible in ViewController
  2. Yet can't be inherited outside target hence causes error.

Image description

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.

Image description

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools