Courses/Swift/Object-Oriented Programming

    Lesson 5 • Intermediate

    Object-Oriented Programming 🏗️

    Master structs vs classes, inheritance, protocols (Swift's version of interfaces), and enums with associated values — the building blocks of every Swift application.

    What You'll Learn in This Lesson

    • • Structs (value types) vs Classes (reference types) — and when to use each
    • • Properties: stored, computed, and property observers
    • • Inheritance, method overriding, and the final keyword
    • • Protocols and protocol-oriented programming
    • • Enums with associated values, raw values, and methods

    1️⃣ Structs vs Classes

    Swift has both structs and classes, but unlike most languages, structs are the default choice. Apple's own frameworks (SwiftUI, most of the standard library) are built heavily on structs. Classes are used when you need inheritance or reference semantics.

    Try It: Structs vs Classes

    Value types, reference types, properties, and computed properties

    Try it Yourself »
    JavaScript
    // Structs vs Classes in Swift
    console.log("=== Structs (Value Types) ===");
    console.log("Structs are COPIED when assigned or passed.");
    console.log();
    
    // Simulating a struct (value type)
    function createPoint(x, y) {
      return { x: x, y: y, toString() { return "(" + this.x + ", " + this.y + ")"; } };
    }
    
    let pointA = createPoint(3, 5);
    let pointB = Object.assign({}, pointA); // copy (struct behavior)
    pointB.x = 10;
    console.log("pointA = " + pointA.toString() + "  // unchanged!");
    console.log("poi
    ...

    2️⃣ Inheritance & Protocols

    Classes support single inheritance. Swift's protocols (similar to interfaces) define a contract that any type can conform to — structs, classes, and even enums. This enables Swift's protocol-oriented programming paradigm.

    Try It: Inheritance & Protocols

    Class hierarchies, method overriding, and protocol conformance

    Try it Yourself »
    JavaScript
    // Inheritance and Protocols in Swift
    console.log("=== Inheritance ===");
    
    class Animal {
      constructor(name, sound) { this.name = name; this.sound = sound; }
      speak() { return this.name + " says " + this.sound; }
      describe() { return "Animal: " + this.name; }
    }
    
    class Dog extends Animal {
      constructor(name, breed) {
        super(name, "Woof!");
        this.breed = breed;
      }
      // Override
      describe() { return "Dog: " + this.name + " (" + this.breed + ")"; }
      fetch(item) { return this.name + " fe
    ...

    3️⃣ Enums with Superpowers

    Swift enums are incredibly powerful compared to other languages. They can have associated values (each case carries different data), raw values, computed properties, and methods. They're used extensively for modeling state machines and API results.

    Try It: Enums

    Associated values, raw values, and enum methods

    Try it Yourself »
    JavaScript
    // Swift Enums — Far More Powerful Than You Think
    console.log("=== Basic Enums ===");
    
    const Direction = { north: "north", south: "south", east: "east", west: "west" };
    let heading = Direction.north;
    console.log("var heading: Direction = ." + heading);
    console.log();
    
    // Enums with associated values (Swift's killer feature!)
    console.log("=== Enums with Associated Values ===");
    class NetworkResult {
      constructor(type, data) { this.type = type; this.data = data; }
    }
    
    function processResult(result
    ...

    ⚠️ Common Mistakes

    ⚠️
    Using classes when structs suffice — Structs are simpler, thread-safe, and faster. Only use classes when you need inheritance or shared state.
    ⚠️
    Forgetting value type semantics — Mutating a struct inside a function requires the mutating keyword.
    💡
    Pro Tip: Use enum Result<Success, Failure> for any operation that can succeed or fail — it's built into Swift!

    📋 Quick Reference — OOP

    ConceptSyntax
    Structstruct Point { var x: Int }
    Classclass Dog: Animal { ... }
    Protocolprotocol Drawable { func draw() }
    Enumenum Result { case success(Data) }
    Overrideoverride func speak()
    Computed propvar area: Double { return w*h }

    🎉 Lesson Complete!

    You've mastered OOP in Swift! Next, learn to build beautiful user interfaces with SwiftUI.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service