Page 235

33. Swift – Access Control


To restrict access to code blocks, modules and abstraction is done through access control. Classes, structures and enumerations can be accessed according to their properties, methods, initializers and subscripts by access control mechanisms. Constants, variables and functions in a protocol are restricted and allowed access as global and local through access control. Access control applied to properties, types and functions can be referred as 'entities'. Access control model is based on modules and source files. Module is defined as a single unit of code distribution and can be imported using the keyword 'import'. A source file is defined as a single source code file with in a module to access multiple types and functions. Three different access levels are provided by Swift language. They are Public, Internal and Private access. Access Levels



Enables entities to be processed with in any source file from their defining module, a source file from another module that imports the defining module.


Enables entities to be used within any source file from their defining module, but not in any source file outside of that module.


Restricts the use of an entity to its own defining source file. Private access plays role to hide the implementation details of a specific code functionality.

Syntax public class SomePublicClass {} internal class SomeInternalClass {} private class SomePrivateClass {}

public var somePublicVariable = 0 internal let someInternalConstant = 0 private func somePrivateFunction() {}

Access Control for Function types Some functions may have arguments declared inside the function without any return values. The following program declares a and b as arguments to the sum() function. Inside the function itself the values for arguments a and b are passed by invoking the function 223

​Swift is just a strong and user-friendly coding language for macOS, iOS, watchOS and tvOS....  


​Swift is just a strong and user-friendly coding language for macOS, iOS, watchOS and tvOS....