{"id":2740,"date":"2026-02-05T12:01:15","date_gmt":"2026-02-05T12:01:15","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2740"},"modified":"2026-02-05T12:01:15","modified_gmt":"2026-02-05T12:01:15","slug":"chapter-77-swift-oop","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/chapter-77-swift-oop\/","title":{"rendered":"Chapter 77: Swift OOP"},"content":{"rendered":"<h3 dir=\"auto\">1. What is OOP? (the clearest possible explanation)<\/h3>\n<p dir=\"auto\"><strong>OOP = Object-Oriented Programming<\/strong> is a way of organizing code by grouping <strong>data<\/strong> and <strong>behavior<\/strong> together into <strong>objects<\/strong>.<\/p>\n<p dir=\"auto\">Instead of writing one giant list of instructions (procedural style), you create <strong>small, self-contained things<\/strong> (objects) that know their own data and know how to do things with that data.<\/p>\n<p dir=\"auto\">Real-life analogy everyone understands:<\/p>\n<ul dir=\"auto\">\n<li>Think of a <strong>smartphone<\/strong> as an object.\n<ul dir=\"auto\">\n<li><strong>Data<\/strong> (properties): screen brightness, battery level, model name, owner<\/li>\n<li><strong>Behavior<\/strong> (methods): takePhoto(), sendMessage(), chargeBattery(), setBrightness(80)<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p dir=\"auto\">You don\u2019t need to know how the inside works \u2014 you just <strong>tell the phone<\/strong> what to do.<\/p>\n<p dir=\"auto\">OOP lets you model your program the same way: create \u201csmart objects\u201d that manage their own state and behavior.<\/p>\n<p dir=\"auto\">Swift supports OOP very well, but it also encourages <strong>value types<\/strong> (structs + enums) and <strong>protocol-oriented programming<\/strong> (POP). Still, understanding classic OOP is extremely important \u2014 many real APIs, UIKit, SwiftUI patterns, and third-party libraries are built around it.<\/p>\n<h3 dir=\"auto\">2. The Four Pillars of OOP \u2014 explained in Swift<\/h3>\n<h4 dir=\"auto\">Pillar 1 \u2013 Encapsulation<\/h4>\n<p dir=\"auto\"><strong>Encapsulation<\/strong> = \u201chide the internal details, expose only what is necessary\u201d<\/p>\n<p dir=\"auto\">In Swift this is done mainly with:<\/p>\n<ul dir=\"auto\">\n<li>private \/ fileprivate \/ internal \/ public<\/li>\n<li>computed properties<\/li>\n<li>methods that control access<\/li>\n<\/ul>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>class BankAccount {\r\n    \/\/ Private \u2014 nobody outside can touch balance directly\r\n    private var balance: Double = 0.0\r\n    \r\n    \/\/ Public read-only property\r\n    var currentBalance: Double {\r\n        balance\r\n    }\r\n    \r\n    \/\/ Designated initializer\r\n    init(initialDeposit: Double) {\r\n        deposit(amount: initialDeposit)\r\n    }\r\n    \r\n    \/\/ Public methods \u2014 controlled access\r\n    func deposit(amount: Double) {\r\n        if amount &gt; 0 {\r\n            balance += amount\r\n            print(\"Deposited \u20b9\\(amount). New balance: \u20b9\\(balance)\")\r\n        }\r\n    }\r\n    \r\n    func withdraw(amount: Double) -&gt; Bool {\r\n        if amount &gt; 0 &amp;&amp; amount &lt;= balance {\r\n            balance -= amount\r\n            print(\"Withdrew \u20b9\\(amount). New balance: \u20b9\\(balance)\")\r\n            return true\r\n        } else {\r\n            print(\"Insufficient funds or invalid amount\")\r\n            return false\r\n        }\r\n    }\r\n}\r\n\r\n\/\/ Usage \u2014 encapsulation in action\r\nlet myAccount = BankAccount(initialDeposit: 10000)\r\nmyAccount.deposit(amount: 5000)\r\nmyAccount.withdraw(amount: 2000)\r\n\/\/ myAccount.balance = -10000   \/\/ \u2190 compile error \u2014 private!\r\nprint(\"Balance: \u20b9\\(myAccount.currentBalance)\")<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Real-life rule<\/strong>:<\/p>\n<blockquote dir=\"auto\">\n<p dir=\"auto\">Make <strong>data private<\/strong> Expose <strong>behavior<\/strong> (methods) that safely change or read the data<\/p>\n<\/blockquote>\n<h4 dir=\"auto\">Pillar 2 \u2013 Abstraction<\/h4>\n<p dir=\"auto\"><strong>Abstraction<\/strong> = \u201cshow only the essential features, hide the complexity\u201d<\/p>\n<p dir=\"auto\">In Swift:<\/p>\n<ul dir=\"auto\">\n<li>Use <strong>protocols<\/strong> to define <strong>what<\/strong> something can do (not how)<\/li>\n<li>Use <strong>classes \/ structs<\/strong> to hide implementation details<\/li>\n<\/ul>\n<p dir=\"auto\">Classic example \u2014 shapes:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>protocol Drawable {\r\n    func draw()\r\n    var area: Double { get }\r\n}\r\n\r\nclass Circle: Drawable {\r\n    let radius: Double\r\n    \r\n    init(radius: Double) {\r\n        self.radius = radius\r\n    }\r\n    \r\n    func draw() {\r\n        print(\"Drawing a circle of radius \\(radius)\")\r\n    }\r\n    \r\n    var area: Double {\r\n        Double.pi * radius * radius\r\n    }\r\n}\r\n\r\nclass Rectangle: Drawable {\r\n    let width: Double\r\n    let height: Double\r\n    \r\n    init(width: Double, height: Double) {\r\n        self.width = width\r\n        self.height = height\r\n    }\r\n    \r\n    func draw() {\r\n        print(\"Drawing a rectangle \\(width)\u00d7\\(height)\")\r\n    }\r\n    \r\n    var area: Double {\r\n        width * height\r\n    }\r\n}\r\n\r\n\/\/ Abstraction in action\r\nlet shapes: [any Drawable] = [\r\n    Circle(radius: 5),\r\n    Rectangle(width: 4, height: 6)\r\n]\r\n\r\nfor shape in shapes {\r\n    shape.draw()\r\n    print(\"Area = \\(shape.area)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">\u2192 The caller <strong>doesn\u2019t care<\/strong> whether it\u2019s a circle or rectangle \u2014 it only cares that it can draw() and has area.<\/p>\n<h3 dir=\"auto\">Pillar 3 \u2013 Inheritance<\/h3>\n<p dir=\"auto\"><strong>Inheritance<\/strong> = a class can <strong>inherit<\/strong> properties &amp; methods from another class (parent \u2192 child)<\/p>\n<p dir=\"auto\">Swift supports <strong>single inheritance<\/strong> only (one direct parent).<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>class Animal {\r\n    let name: String\r\n    \r\n    init(name: String) {\r\n        self.name = name\r\n    }\r\n    \r\n    func makeSound() {\r\n        print(\"\\(name) makes a sound\")\r\n    }\r\n}\r\n\r\nclass Dog: Animal {\r\n    override func makeSound() {\r\n        print(\"\\(name) says Woof! \ud83d\udc36\")\r\n    }\r\n    \r\n    func wagTail() {\r\n        print(\"\\(name) wags tail happily\")\r\n    }\r\n}\r\n\r\nclass Cat: Animal {\r\n    override func makeSound() {\r\n        print(\"\\(name) says Meow! \ud83d\udc31\")\r\n    }\r\n}\r\n\r\nlet dog = Dog(name: \"Bruno\")\r\nlet cat = Cat(name: \"Luna\")\r\n\r\ndog.makeSound()     \/\/ Bruno says Woof! \ud83d\udc36\r\ncat.makeSound()     \/\/ Luna says Meow! \ud83d\udc31\r\ndog.wagTail()       \/\/ Bruno wags tail happily<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>When to use inheritance (modern Swift view)<\/strong>:<\/p>\n<ul dir=\"auto\">\n<li><strong>Yes<\/strong>: clear \u201cis-a\u201d relationship (Dog is an Animal)<\/li>\n<li><strong>Yes<\/strong>: you want to share <strong>common behavior<\/strong> &amp; <strong>state<\/strong><\/li>\n<li><strong>No<\/strong>: just to reuse code \u2014 prefer <strong>composition<\/strong> (has-a) or <strong>protocols<\/strong><\/li>\n<\/ul>\n<h3 dir=\"auto\">Pillar 4 \u2013 Polymorphism<\/h3>\n<p dir=\"auto\"><strong>Polymorphism<\/strong> = \u201cmany forms\u201d \u2014 same method name, different behavior depending on the actual object type.<\/p>\n<p dir=\"auto\">This happens automatically thanks to <strong>inheritance<\/strong> + <strong>protocols<\/strong>.<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let animals: [Animal] = [Dog(name: \"Bruno\"), Cat(name: \"Luna\"), Animal(name: \"Generic\")]\r\n\r\nfor animal in animals {\r\n    animal.makeSound()     \/\/ different sound for each!\r\n}\r\n\r\n\/\/ Bruno says Woof! \ud83d\udc36\r\n\/\/ Luna says Meow! \ud83d\udc31\r\n\/\/ Generic makes a sound<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Protocol-based polymorphism<\/strong> (modern Swift favorite):<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>protocol Speakable {\r\n    func speak()\r\n}\r\n\r\nextension Dog: Speakable {\r\n    func speak() { print(\"Woof!\") }\r\n}\r\n\r\nextension Cat: Speakable {\r\n    func speak() { print(\"Meow!\") }\r\n}\r\n\r\nlet speakers: [any Speakable] = [Dog(name: \"Bruno\"), Cat(name: \"Luna\")]\r\nspeakers.forEach { $0.speak() }<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">5. Real-life examples \u2014 OOP patterns you will actually use<\/h3>\n<h4 dir=\"auto\">Example 1 \u2013 UIViewController hierarchy (UIKit classic)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>class BaseViewController: UIViewController {\r\n    override func viewDidLoad() {\r\n        super.viewDidLoad()\r\n        setupUI()\r\n    }\r\n    \r\n    func setupUI() {\r\n        view.backgroundColor = .systemBackground\r\n    }\r\n}\r\n\r\nclass ProfileViewController: BaseViewController {\r\n    override func setupUI() {\r\n        super.setupUI()\r\n        \/\/ add profile specific UI\r\n        title = \"Profile\"\r\n    }\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 2 \u2013 Payment processor (very common backend \/ fintech)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>protocol PaymentProcessor {\r\n    func process(amount: Double) throws -&gt; String\r\n}\r\n\r\nclass RazorpayProcessor: PaymentProcessor {\r\n    func process(amount: Double) throws -&gt; String {\r\n        \/\/ simulate Razorpay\r\n        return \"RZP_TXN_\\(UUID().uuidString.prefix(8))\"\r\n    }\r\n}\r\n\r\nclass PaytmProcessor: PaymentProcessor {\r\n    func process(amount: Double) throws -&gt; String {\r\n        \/\/ simulate Paytm\r\n        return \"PTM_\\(Int(Date().timeIntervalSince1970))\"\r\n    }\r\n}\r\n\r\nclass PaymentService {\r\n    let processor: PaymentProcessor\r\n    \r\n    init(processor: PaymentProcessor) {\r\n        self.processor = processor\r\n    }\r\n    \r\n    func pay(amount: Double) {\r\n        do {\r\n            let transactionID = try processor.process(amount: amount)\r\n            print(\"Payment successful! Transaction: \\(transactionID)\")\r\n        } catch {\r\n            print(\"Payment failed: \\(error)\")\r\n        }\r\n    }\r\n}\r\n\r\n\/\/ Usage\r\nlet service = PaymentService(processor: RazorpayProcessor())\r\nservice.pay(amount: 999.99)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">6. Quick Summary \u2013 The Four Pillars in Swift<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"xs\">Pillar<\/th>\n<th data-col-size=\"lg\">Swift implementation<\/th>\n<th data-col-size=\"lg\">Real-life feeling<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"xs\"><strong>Encapsulation<\/strong><\/td>\n<td data-col-size=\"lg\">private, fileprivate, computed properties<\/td>\n<td data-col-size=\"lg\">Hide internal state, expose safe methods<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"xs\"><strong>Abstraction<\/strong><\/td>\n<td data-col-size=\"lg\">Protocols, protocol extensions<\/td>\n<td data-col-size=\"lg\">Define \u201cwhat\u201d not \u201chow\u201d<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"xs\"><strong>Inheritance<\/strong><\/td>\n<td data-col-size=\"lg\">class Child: Parent<\/td>\n<td data-col-size=\"lg\">\u201cis-a\u201d relationship (Dog is an Animal)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"xs\"><strong>Polymorphism<\/strong><\/td>\n<td data-col-size=\"lg\">method overriding + protocol conformance<\/td>\n<td data-col-size=\"lg\">Same message \u2192 different behavior<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">7. Small Practice \u2013 Try these<\/h3>\n<ol dir=\"auto\">\n<li>Create a base class Vehicle with makeSound() Create two subclasses: Car (\u201cVroom!\u201d) and Bike (\u201cVruum-vruum!\u201d) Put them in an array [Vehicle] and call makeSound() on each<\/li>\n<li>Create a protocol Payable with method processPayment(amount:) Implement it for two payment methods (Razorpay, Paytm)<\/li>\n<li>Create a class Employee with name, salary (private) Add method giveRaise(percent:) that safely increases salary<\/li>\n<\/ol>\n<p dir=\"auto\">Paste your code here if you want feedback or want to see more elegant versions!<\/p>\n<p dir=\"auto\">What would you like to explore next?<\/p>\n<ul dir=\"auto\">\n<li><strong>Protocol-oriented programming<\/strong> (POP) vs classic OOP<\/li>\n<li><strong>Struct vs Class<\/strong> \u2014 when to choose which<\/li>\n<li><strong>Inheritance<\/strong> vs <strong>composition<\/strong> (modern preference)<\/li>\n<li><strong>Access control<\/strong> (private, fileprivate, internal, public, open)<\/li>\n<li>OOP in <strong>SwiftUI<\/strong> (ObservableObject, @StateObject\u2026)<\/li>\n<li>Or move to another topic (optionals, arrays, closures, switch\u2026)<\/li>\n<\/ul>\n<p dir=\"auto\">Just tell me \u2014 we\u2019ll continue in the same clear, detailed, patient style \ud83d\ude0a<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. What is OOP? (the clearest possible explanation) OOP = Object-Oriented Programming is a way of organizing code by grouping data and behavior together into objects. Instead of writing one giant list of instructions&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76],"tags":[],"class_list":["post-2740","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2740","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/comments?post=2740"}],"version-history":[{"count":1,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2740\/revisions"}],"predecessor-version":[{"id":2741,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2740\/revisions\/2741"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2740"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2740"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2740"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}