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.swift323 chars16 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