How to create a class and subclass in Swift
Creating a class in swift
A class is a user-defined data type that includes local methods and properties. It’s a blueprint to create objects.
Classes are an important concept in object-oriented programming. A class contains both data (variables) called properties and methods (functions defined inside a class).
We use the keyword class to define a class in Swift.
Syntax
class className{
// methods, variables
}
Example
class Person {var name:Stringvar age:Intinit(name:String, age:Int){self.name = nameself.age = age}}let person = Person(name: "john", age: 23)print("Person(name:\(person.name), age:\(person.age))")
Explanation
- Lines 1–9: We create a class
Personthat has two members,nameandage. We use the initializerinit()method to initialize the values of the membersnameandage. - Line 11: An instance of the
Personclass is created withnameasjohnandageas23. - Line 12: We can access the properties using the dot (
.) notation. The values of the variables of thepersonobject are printed.
Creating a subclass in Swift
Inheritance in object-oriented programming is the ability of a class to derive or inherit methods and properties from another class. There are two types of categories of classes that involve inheritance:
- Base class or parent class: A class whose properties are inherited by the derived class.
- Derived class or subclass or child class: A class that inherits properties from another class.
Syntax
In Swift, we use the colon : to inherit a class from another class.
class ChildClass: BaseClass {
// methods, variables
}
Example
class Vehicle {var brandName: String = "Ferrari"func honk(){print("Honking")}}class Car: Vehicle{var model: String = "Daytona"func display(){print("Car[brand=\(brandName), model=\(model)")}}let car = Car()car.display()car.honk()
Explanation
- Lines 1–7: A
Vehicleclass is defined that has the attributebrandNameand the methodhonk(). - Lines 9–19: A
Carclass is defined that inherits fromVehicleclass. It has its own attributes and methods. - Line 17: An instance of the
Carclass calledcaris created. - Line 18: The
display()method of theCarclass is invoked. - Line 19: The
honk()method of theVehicleclass is invoked on thecarinstance as theCarclass inherits from theVehicleclass.