create a subclass in swift

To create a subclass in Swift, we use the class keyword followed by the subclass name, a colon, and the name of the superclass that we want to inherit from. Here is an example:

main.swift
class Vehicle {
    var currentSpeed: Double = 0.0
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    }
}

class Bicycle: Vehicle {
    var hasBasket: Bool = false
}

let myBicycle = Bicycle()
myBicycle.currentSpeed = 15.0
myBicycle.hasBasket = true
print(myBicycle.description)
323 chars
16 lines

In the example above, we have a superclass called Vehicle with two properties (currentSpeed and description). We then create a subclass called Bicycle that inherits from Vehicle using the syntax class Bicycle: Vehicle.

We add a new property to the Bicycle class called hasBasket. We then create an instance of Bicycle called myBicycle and set its currentSpeed and hasBasket properties. When we print myBicycle.description, it outputs "traveling at 15.0 miles per hour", which is the description property of its superclass Vehicle.

This demonstrates how to create a subclass in Swift that inherits from a superclass and adds its own properties and behavior.

gistlibby LogSnag