Classes in Swift

From the Swift cheat sheet · Structs & Classes · verified Jul 2026

Classes

Reference types with inheritance

swift
// Class definition
class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) mph"
    }

    func makeNoise() {
        // Base implementation
    }

    init(speed: Double) {
        self.currentSpeed = speed
    }
}

// Inheritance
class Bicycle: Vehicle {
    var hasBasket = false

    override func makeNoise() {
        print("Ring ring!")
    }
}

// Reference semantics
let bike1 = Bicycle(speed: 15)
let bike2 = bike1  // Same reference
bike2.currentSpeed = 20
print(bike1.currentSpeed)  // 20
💡 Classes are reference types - variables share same instance
⚡ Use final to prevent inheritance or overriding
📌 Deinitializers run when instances are deallocated
🟢 Type casting with as? safely attempts downcasting

Continue with Swift

Save the full cheat sheet or work through every related task.

More Swift tasks

Back to the full Swift cheat sheet