Swift OOPs (Object-Oriented Programming)


What is OOP?


OOP (Object-Oriented Programming) is a programming paradigm that uses objects and classes to structure code. It helps in organizing complex programs, reusing code, and improving readability.



4 Main Pillars of OOP in Swift:

  • Encapsulation – Wrapping data and methods into a single unit (class).
  • Abstraction – Hiding complex implementation details and showing only necessary features.
  • Inheritance – Acquiring properties and methods from another class.
  • Polymorphism – Ability to use a function in different ways (overriding, overloading).

1. Classes and Objects in Swift


Class Syntax

class Person {
     var nameString
     var ageInt

     init(nameStringageInt{
         self.name = name
         self.age = age
     }

     func greet() {
         print( "Hello, my name is \(name).  I am \(age) years old.")
     }
}

let person1 = Person( name"John"age25)
person1.greet()

Output


Hello, my name is John. I


2. Encapsulation in Swift


Private, Public, Internal access control to restrict access to data.

class BankAccount {
     private var balanceDouble = 0.0

     func deposit(amountDouble{
         balance += amount
     }

     func getBalance() -> Double {
         return balance
     }
}

let account = BankAccount()
account.deposit(amount1000)
print(account.getBalance())

Output


1000.0


3. Inheritance in Swift

One class (child) can inherit properties and methods from another (parent).

class Vehicle {
     var brandString

     init(brandString{
         self.brand = brand
     }

     func honk() {
         print("Beep! Beep!")
     }
}

class CarVehicle {
     var modelString

     init(brandStringmodelString{
         self.model = model
         super.init(brandbrand)
     }

     func display() {
         print("Brand: \(brand), Model: \(model)")
     }
}

let car1 = Car(brand"Toyota"model"Corolla")
car1.honk() // Output: Beep! Beep!
car1.display()

Output


Beep! Beep!
Brand: Toyota, Model: Corolla


4. Polymorphism in Swift


Method Overriding

class Animal {
     func sound() {
         print("Animal sound")
     }
}

class DogAnimal {
     override func sound() {
         print("Bark")
     }
}

let dog = Dog()
dog.sound() // Output: Bark

Output


Bark


5. Abstraction in Swift using Protocols

Protocol defines a blueprint of methods and properties.

protocol Drawable {
     func draw()
}

class CircleDrawable {
     func draw() {
         print("Drawing a circle")
     }
}

class SquareDrawable {
     func draw() {
         print("Drawing a square")
     }
}

let shapes: [Drawable] = [Circle(), Square()]
for shape in shapes {
     shape.draw()
}

Output


Drawing a circle
Drawing a square


6. Access Modifiers in Swift


Modifier Access Level
open Accessible and subclassable anywhere
public Accessible anywhere
internal Accessible within same module/project
fileprivate Accessible within same file
private Accessible within same class/struct/extension