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 name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func greet() {
print(
"Hello, my name is \(name).
I am \(age) years old.")
}
}
let person1 = Person(
name: "John", age: 25)
person1.greet()
Output
2. Encapsulation in Swift
Private, Public, Internal access control to restrict access to data.
class BankAccount {
private var balance: Double = 0.0
func deposit(amount: Double) {
balance += amount
}
func getBalance() -> Double {
return balance
}
}
let account = BankAccount()
account.deposit(amount: 1000)
print(account.getBalance())
Output
3. Inheritance in Swift
One class (child) can inherit properties and methods from another (parent).
class Vehicle {
var brand: String
init(brand: String) {
self.brand = brand
}
func honk() {
print("Beep! Beep!")
}
}
class Car: Vehicle {
var model: String
init(brand: String, model: String) {
self.model = model
super.init(brand: brand)
}
func display() {
print("Brand: \(brand), Model: \(model)")
}
}
let car1 = Car(brand: "Toyota", model: "Corolla")
car1.honk() // Output: Beep! Beep!
car1.display()
Output
Brand: Toyota, Model: Corolla
4. Polymorphism in Swift
Method Overriding
class Animal {
func sound() {
print("Animal sound")
}
}
class Dog: Animal {
override func sound() {
print("Bark")
}
}
let dog = Dog()
dog.sound() // Output: Bark
Output
5. Abstraction in Swift using Protocols
Protocol defines a blueprint of methods and properties.
protocol Drawable {
func draw()
}
class Circle: Drawable {
func draw() {
print("Drawing a circle")
}
}
class Square: Drawable {
func draw() {
print("Drawing a square")
}
}
let shapes: [Drawable] = [Circle(), Square()]
for shape in shapes {
shape.draw()
}
Output
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 |