Swift access control


Release date:2023-12-06 Update date:2023-12-11 Editor:admin View counts:268

Label:

Swift access control

Access control can limit the level of access to your code from other source files or modules.

You can explicitly set access levels for individual types (classes, structures, enumerations), as well as properties, functions, initialization methods, basic types, subscript indexes, and so on.

The protocol can also be limited to a certain range of use, including globalconstants, variables and functions in the protocol.

Access control is based on modules and source files.

A module refers to a Framework or Application that is built and released as a separate unit. A module in Swift can use the import keyword introduces another module.

The source file is a single source file, which usually belongs to a module, and the source file can contain the definitions of multiple classes and functions.

Swift provides four different levels of access for entities in your code: publicinternalfileprivateprivate .

Access level

Define

public

You can access any entity in the source file of your own module, and others can access all entities in the source file by introducing the module.

internal

You can access any entity in the source file in your module, but others cannot access the entity in the source file in the module.

fileprivate

The file is private and can only be used in the current source file.

private

It can only be accessed in a class and cannot be accessed outside the scope of the class or structure.

Public is the highest access level and private is the lowest access level.

Grammar

By modifier publicinternalfileprivateprivate todeclare the access level of the entity:

Example

publicclassSomePublicClass{}internalclassSomeInternalClass{}
fileprivateclassSomeFilePrivateClass{}privateclassSomePrivateClass
{}publicvarsomePublicVariable=0internalletsomeInternalConstant=
0fileprivatefuncsomeFilePrivateFunction(){}privatefuncsomePrivateFunction(){}

Unless otherwise specified, entities use the default access level internal .

Unspecified access level defaults to internal

classSomeInternalClass{}// Access level is
internalletsomeInternalConstant=0// Access level is internal

Access to function type

The access level of a function needs to be based on the access level of the function’s parameter type and return type.

The following example defines a file named someFunction global functionwithout explicitly declaring its access level.

func someFunction() -> (SomeInternalClass, SomePrivateClass) {
    // Function implementation
}

One of the classes in the function SomeInternalClass the access level of internal Oh, another one. SomePrivateClass the access level of``private`` . So according to the principle of tuple access level, the tuple access level is private the access level of the tuple is the sameas the type with the lowest access level in the tuple.

Because the access level of the return type of this function is private .So you have to use the private modifier to explicitly declare the function:

private func someFunction() -> (SomeInternalClass, SomePrivateClass) {
    // Function implementation
}

Declare the function as public or internal or use the default access level internal is all wrong, because if you do, you can’t access private the return value of the level.

Enumerate type access permissions

The access level of the members in the enumeration inherits from the enumeration, and you cannot declare different access levels separately for the members of the enumeration.

Example

For example, in the following example, if the enumeration Student is explicitly declared as a public level, then its members Name and Mark have the same access level as public :

Example

publicenumStudent{caseName(String)caseMark(Int,Int,Int)}
varstudDetails=Student.Name("Swift")varstudMarks=Student.Mark
(98,97,95)switchstudMarks{case.Name(letstudName):
print("Student Name:\\(studName).")case.Mark(letMark1,letMark2,letMark3):
print("Student Achievements:\\(Mark1),\\(Mark2),\\(Mark3)")}

The output of the above program execution is as follows:

Student Achievements: 98,97,95

Subclass access permission

The access level of the subclass must not be higher than that of the parent class. For example, if the access level of the parent class is internal, theaccess level of the subclass cannot be declared as public.

Example

publicclassSuperClass{fileprivatefuncshow(){print("superclass")}}//
Access level cannot be higher than superclass public >
internalinternalclassSubClass:SuperClass{overrideinternalfuncshow()
{print("subclass")}}letsup=SuperClass()sup.show()letsub=SubClass()sub.show()

The output of the above program execution is as follows:

Superclass
Subclass

Constant, variable, attribute, subscript access

Constants, variables, and properties cannot have a higher level of access than their types.

For example, you define a public level, but its type is private level, which is not allowed by the compiler

Similarly, the subscript cannot have a higher level of access than the indextype or return type.

If the definition types of constants, variables, properties, and subscript indexes are private level, then they must explicitly state that the access level is private :

private var privateInstance = SomePrivateClass()

Getter and Setter acc

Constant, variable, attribute, subscript index Getters and Setters inherits from the access level of the members to which they belong.

Setter the access level of can be lower than the corresponding Getter so that you can control the read and write permissions for variables, properties, or subscript indexes

Example

classSamplepgm{fileprivatevarcounter:Int=0{willSet(newTotal){print
("counter:\\(newTotal)")}didSet{ifcounter>oldValue{print("Newly added quantity\\(counter
-
oldValue)")}}}}letNewCounter=Samplepgm()NewCounter.counter=100NewCounter.counter=800

counter the access level of fileprivate which can be accessed within the file

The output of the above program execution is as follows:

Counter: 100
Add 100 new quantities
Counter: 800
Newly added quantity of 700

Constructor and default constructor access

Initialization

We can declare the access level to the custom initialization method, but nothigher than the access level of the class to which it belongs. With the exception of the necessary constructor, its access level must be the same asthat of the class to which it belongs.

Like a function or method parameter, the access level of the initialization method parameter cannot be lower than that of the initialization method.

Default initialization method

Swift provides a default no-parameter initialization method for both structures and classes, which is used to provide assignments to all their properties, but does not give body values.

The access level of the default initialization method is the same as that ofthe type it belongs to.

Example

In each subclass init() method before using the required keyword declares access permissions.

Powered by TorCMS (https://github.com/bukun/TorCMS).