DEV Community

Harsh Prajapat
Harsh Prajapat

Posted on

SOLID Principles in iOS (Swift)

SOLID Principles in iOS (Swift) — Explained with Simple Examples

SOLID is a set of 5 design principles used to write clean, scalable, reusable, and maintainable code in iOS apps.

These principles are very important in:

UIKit
SwiftUI
MVVM
Clean Architecture
Large-scale apps

  1. S — Single Responsibility Principle (SRP) Meaning

A class should have only one reason to change.

A class should do only one job.

❌ Bad Example

class UserManager {

    func fetchUser() {
        print("Fetch user from API")
    }

    func saveUserToDatabase() {
        print("Save user in DB")
    }

    func sendEmail() {
        print("Send email to user")
    }
}
Enter fullscreen mode Exit fullscreen mode

2. O — Open/Closed Principle (OCP)

  • The Open/Closed Principle (OCP) states that software entities (classes, modules, and functions) should be open for extension, but closed for modification. This means you should be able to add new functionality or behaviors without altering the existing, tested source code.

W*hy is OCP important?*

Prevents Bugs: Touching working, tested code always carries the risk of introducing unintended bugs.

Maintainability: Codebases become much easier to manage, scale, and test as they grow.

Given multiple sentences, extract all words into one vector

var names = ["iOS Developer", "Android Developer", ".NET Developer"]

let sentence = "Swift is fun to learn"
let words = sentence.split(separator: " ")
print(words)

// ["Swift", "is", "fun", "to", "learn"]

for str in names {
    let words = str.split(separator: " ")
    for char in words {
        print(char)
    }
}

// iOS
// Developer
// Android
// Developer
// .NET
// Developer
Enter fullscreen mode Exit fullscreen mode

Top comments (0)