BudiBadu Logo
Samplebadu

Swift by Example: Classes

Swift 5.x

Dive into Swift classes with this sample code demonstrating reference type behavior, property declarations, computed properties, method definitions, class inheritance using colon syntax, method overriding with override keyword, and shared instance references.

Code

class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at (currentSpeed) miles per hour"
    }
    func makeNoise() {
        // do nothing - an arbitrary vehicle doesn't necessarily make a noise
    }
}

class Bicycle: Vehicle {
    var hasBasket = false
    
    // Overriding a method
    override func makeNoise() {
        print("Ring Ring!")
    }
}

let bicycle = Bicycle()
bicycle.hasBasket = true
bicycle.currentSpeed = 15.0
print("Bicycle: (bicycle.description)")
bicycle.makeNoise()

// Classes are reference types
let bike2 = bicycle
bike2.currentSpeed = 20.0
print(bicycle.currentSpeed) // 20.0 (both refer to same instance)

Explanation

Classes are the building blocks of flexible constructs. They support inheritance, allowing one class to inherit the characteristics of another. Classes in Swift are reference types, meaning that when you assign a class instance to a variable or pass it to a function, you are passing a reference to the same existing instance, not a copy.

Classes can have properties (variables attached to the class) and methods (functions attached to the class). Computed properties, like description in the example, calculate a value rather than storing it. Subclasses can override methods and properties of their superclass using the override keyword.

Unlike structures, classes support deinitializers (deinit) to clean up resources before the instance is deallocated. They also support reference counting (ARC) to manage memory automatically.

Code Breakdown

3-5
var description: String { ... } defines a computed property.
11
class Bicycle: Vehicle creates a subclass inheriting from Vehicle.
15
override func makeNoise() replaces the superclass method implementation.
23-24
let bike2 = bicycle creates a reference to the same instance, not a copy.