Swift Access Control

  Total Views : 105
  Comments : 0
  Keywords : Swift access control to restrict access to methods, properties in code, Swift access control to hide implementation details and show essential features

Here we will learn access control in swift with examples and how to use swift access control, different types of swift access levels, access controls for function types, action controls for enumerations, actions controls for classes and subclasses, action controls for initializers, protocols, generics in swift with examples.

Swift Access Control

In swift, Access control is used to define a restriction on particular part of code to access any method, properties, types and functions based on programmer choice. The access control feature in swift enable us to hide the implementation details of our code and show only essentials features.

 

In swift, we can use access control to set an access level restrictions on individual types like structures, functions, variables, enumerations, classes and properties, methods, etc. We can also restrict the protocols using access controls. Swift offers various types of access control to restrict the code access.

 

Generally, in swift access control model is based on the combination of modules and source files.

 

In swift, Module is defined as a single unit of code distribution. The application or a framework which built on Xcode will be treated as a separate module and we can use it in another applications or modules by using swift import keyword.

Swift Access Levels

Swift provides a five different access levels to implement a restrictions in our code and these access levels are belonging to the source file and relative to the module that source file belongs to.

 

  • Open or Public access will enable entities to be used in any source file from the defined module and also in a source file from another module that import the defining module. 
  • Internal access will enable entities to be used within any source file from their defining module, but not in any source file outside of that module. We can typically use internal when we define an app or framework internal structure.
  • File-private access will restrict the use of an entity to its own defining source file. We can use File-private access to hide the implementation details of a specific functionality when those details are used inside within an entire file.
  • Private access will enable entities to be used only within the enclosing declaration and we can use Private access to hide the implementation details of specific functionality when those details are used only within a single declaration.

In swift, Open is the least restrictive access level and Private is the high restrictive access level.

 

Note: No entity can be defined under another entity that has a high restriction access level.

 

Generally, in swift if we didn’t define any explicit access level for an entity by default it will consider as an internal access level. So if we are implementing any individual applications that we don’t need to make it available for any other app modules then the default access level of internal will match this requirement, we don’t need to define any explicit access level for that application.

 

In case if we are implementing any framework which need to make it available for other modules then we need to define it as an Open or Public access levels.

Swift Access Control Syntax

In swift, we can define the access levels for an entity by using open, public, internal, fileprivate or private access controls before the entity.

 

Following are the syntaxes of defining an entities with different access controls in swift programming language.

 

public var variableName = 0

internal let variableName = 0

fileprivate func somefunction() {}

 

private class studentClass {}

public class studentClass {}

internal class studentclass {}

We can also define an entities without explicit access controls, by default those entities will use internal access control.

 

Following are the sample syntaxes of defining an entities without explicit modifiers.

 

var variableName = 0      // Default Internal

class studentClass {}        // Default Internal

Swift Access Control for Function Types

In swift, we can define an explicit access levels for functions as a part of its definitions based on our requirements to allow or disallow functions access outside of the module or a file. 

 

Swift allows us to define a functions with private, public, internal or fileprivate access controls based on the programmers requirement.

 

Following is the example of defining a function with private access control to restrict the access of function within the current module.

 

private func mathoperators(a: Int, b: Int, c:Int, d:Int) {

let a = a + b

let b = a - b

let c = a * b

let d = a / b

print(a, b,c,d)

}

mathoperators(a: 23, b: 44, c: 44, d: 555)

If you observe above example we defined a function mathoperators with private access control to restrict the access within current module or file.

 

When we run above example in swift playground we will get a result like as shown below

 

67 23 1541 2

This is how we can define an access controls for functions based on our requirements in swift programming language.

Swift Access Control for Enumerations

Swift allows us to define access control for enumeration. The individual cases in enumeration will receive same access level of enumeration. We don’t have any option to define a separate access level for individual enumeration cases. 

 

Following is the example of defining an enumeration with public access control to access enumeration entity in application module based on our requirements.

 

public enum person {

case personid(Int)

case FullName(String)

case Gender(String)

}

var personid = person.personid(1)

var personname = person.FullName("Suresh Dasari")

var personegender = person.Gender("Male")

switch personname {

case .personid(let id):

print("Person ID: \(id)")

case .FullName(let Name):

print("Person name: \(Name)")

case .Gender(let gender):

print("Person Gender: \(gender)")

default:

print("Empty")

}

When we run above program in swift playground we will get a result like as shown below

 

Person name: Suresh Dasari

This is how we can use access modifiers in enumeration to allow or disallow access of enumeration in application modules based on our requirements.

Swift Access Control for Classes and SubClasses

Swift allows us to perfectly control the classes and subclasses in any context using access controls. In swift, subclass cannot have a higher access level than its superclass because it inherits from parent class.

 

By using accessing controls we can override a class members like method, property, initializer, etc. which are available in current context.

 

Following is the example defining a class, subclass and overriding a superclass methods in subclass using access controls in swift programming language.

 

public class userInfo {

public func userdetails() {

print("Name: Suresh Dasari")

}

}

internal class locationInfo: userInfo  {

override internal func userdetails() {

print("Location: Hyderabad")

}

}

let cc = userInfo()

cc.userdetails()

let ss = locationInfo()

ss.userdetails()

If you observe above example we created a class userInfo, subclass locationInfo and overriding a userInfo class method userdetails() in locationInfo subclass using access controls.

 

When we run above program in swift playground we will get a result like as shown below

 

Name: Suresh Dasari

Location: Hyderabad

This is how we can use access controls in classes and subclasses to restrict access levels based on our requirements in swift programming language.

Swift Access Control for Constants and Variables

In swift, we can define any variable or constant with required access control of our choice. Before declaring any variable or constant we need to add an access control and then declare the variable.

 

Following is the example of defining a constants and variables with access controls to restrict its access in current context based on our requirements in swift programming language.

 

public struct userInfo{

public let name: String

var location: String

private let result: String

public init(_ name: String, location: String) {

self.name = name

self.location = location

self.result = "\(name), \(location)"

print(result)

}

}

let user = userInfo("Suresh Dasari", location: "Hyderabad")

print("Name: \(user.name)")

print("Location: \(user.location)")

If you observe above example we defined a constant name and the variable location with access control public and we can access those values outside of structure. Here we defined a constant result with access control private due to that it’s not possible for us to access result constant outside of the structure.

 

When we run above program in swift playground we will get a result like as shown below

 

Suresh Dasari, Hyderabad

Name: Suresh Dasari

Location: Hyderabad

This is how we can define a constants and variables with access controls to restrict its access within current context based on our requirements in swift programming language. 

Swift Access Control for Getter and Setter

In swift, the getter and setter properties of constants or variables will receive the same access level of constants or variables they belong to. We can set a lower access level for setter than its corresponding getter, to restrict the read-write scope of that variable or property.

 

Following is the example of adding access controls to getter and setter properties of constants or variables in swift programming language.

 

class getterandsetter {

private var number1 = 123

internal var number2 : Int {

get {

return number1

}

set (newnumber) {

precondition(newnumber > 0, "Not allowed")

number1 = newnumber

}

}

}

let cc = getterandsetter()

cc.number2 = 345

print(cc.number2)

If you observe above example we defined getter and setter with access controls and performing custom operations based on our requirements. In case if we pass number2 values less than or equal to 0 then we will get a precondition error.

 

When we run above example in swift playground we will get a result like as shown below

 

345

This is how we can use access controls in constant or variable getter and setter properties based on our requirements in swift programming language.

Swift Access Control for Initializers

In swift, custom initializers can be assigned an access level less than or equal to the type that they initialize but required initializers must have the same access level as the class it belongs to.

 

Following is the example of defining an access levels for custom initializers in swift programming language.

 

class class1 {

required init() {

let num = 123

print(num)

}

}

class class2: class1 {

required init() {

let num2 = 100

print(num2)

}

}

let cls1 = class1()

let cls2 = class2()

When we run above program in swift playground we will get a result like as shown below

 

123

100

123

The default initializer in swift has the same access level as the type it initializes, unless that type is defined as public. For a type that is defined as public, the default initializer will be considered as an internal. In case if we want a public type to be initializable with a no-argument initializer when used in another module, we must explicitly provide a public no-argument initializer yourself as part of the type’s definition.

 

This is how we can use access controls in initializers based on our requirements in swift programming language.

Swift Access Control for Protocols

Access Control is also defining in protocols but protocols must conformance the type protocol when we declare in our class.

 

Following is the example of defining a protocol fullname with public modifier and declare the function in it. After that we adopted a protocol fullname in class stu and implemented a protocol function display() in class based on our requirements. By creating a class instance we can access the function directly because we defined a protocol with public modifier.

 

public protocol fullname {

func display()

}

class stu: fullname {

func display() {

print("Trishika Dasari")

}

}

let ss = stu()

ss.display()

When we run above program in swift playground we will get a result like as shown below

 

Trishika Dasari

This is how we can use access controls with protocols in swift programming language based on our requirements.

Swift Access Control Extension

In swift, we can extend a class, enumeration or a structure in current context using extension. If we extend any internal or public type, the new member type which we will add have default access level of internal. If we extend with private type, the new members will have a default access level of private.

 

In swift, we can mark an extension with explicit level modifier to set a new default access level for all members defined within the extension. In case if we are using an extension to add protocol conformance, for that we should not provide an explicit access-level modifier.

 

Following is the example of using access controls with extensions in swift programming language.

 

public struct person { }

extension person {

var name: String { return "Suresh Dasari" }

}

public extension person {

var location: String { return "Hyderabad" }

}

let p = person()

print(p.name)

print(p.location)

If you observe above example we using access controls with extensions to extend the functionality of structure person based on our requirements.

 

When we run above program in swift playground we will get a result like as shown below

 

Suresh Dasari

Hyderabad

This is how we can use access controls with extensions in swift programming language based on our requirements.

Swift Access Control for Generics

In swift, Generics also allow programmer to specify their access control level to access type parameters and constraint in a function.

 

Following is the example of using access controls with generics in swift programming language.

 

public struct Name<T> {

var Student = [T]()

public mutating func push(item: T) {

Student.append(item)

}

}

var s = Name<String>()

s.push(item: "Swift")

print(s.Student)

s.push(item: "C Programming")

print(s.Student)

When we run above program in swift playground we will get a result like as shown below

 

["Swift"]

["Swift", "C Programming"]

This is how we can use access controls with generics to define a restrictions based on our requirements in swift programming language. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User