Objective-oriented Programming Principles in Swift

·

2 min read

Object-oriented programming has four main principles: Encapsulation, Inheritance, abstraction, and polymorphism.

Let's see how these four critical principles of Object-Oriented Programming (OOP) apply in Swift.

1. Encapsulation

Encapsulation is an OOP principle that binds together data and functions that manipulate the data. It shields the data from direct access by outside functions or code.

In Swift, encapsulation is achieved using classes, structs, and enumerations. Data is encapsulated in properties, and functions are encapsulated in methods.

Example:

class Shape {
    private var color: String

    init(color: String) {
        self.color = color
    }

    public func getColor() -> String {
        return self.color
    }
}

In the above example, color is encapsulated within the Shape class and is accessed through a public method.

2. Inheritance

Inheritance is a principle where a class (subclass or child class) inherits properties and methods of another class (superclass or parent class).

Swift supports single inheritance, where a class can inherit from only one superclass.

Example:

class Shape {
    var color: String

    init(color: String){
        self.color = color
    }

    func displayColor() {
        print("The color of the shape is \(self.color)")
    }
}

class Circle: Shape {
    var radius: Double

    init(color: String, radius: Double) {
        self.radius = radius
        super.init(color: color)
    }

    // Additional methods specific to Circle
}

In this example, Circle is a subclass of Shape and inherits Shape's properties and functions.

3. Abstraction

Abstraction refers to representing essential features without including the background details. It helps reduce complexity and increase efficiency by providing a general view of the object.

Swift provides protocols and protocol-oriented programming to foster a high level of abstraction in the code. It provides a blueprint for properties, methods, and other responsibilities.

Example:

protocol Shape {
    var color: String { get set }
    func displayColor()
}

class Circle: Shape {
    var color: String
    var radius: Double

    init(color: String, radius: Double) {
        self.color = color
        self.radius = radius
    }

    func displayColor() {
        print("The color of the circle is \(self.color)")
    }
}

Here Shape is a protocol, i.e., an abstract class that provides a blueprint for methods, properties, and other functionalities. Circle is a class that conforms to this protocol.