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:String
var age:Int
init(name:String, age:Int){
self.name = name
self.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 Person that has two members, name and age. We use the initializer init() method to initialize the values of the members name and age.
  • Line 11: An instance of the Person class is created with name as john and age as 23.
  • Line 12: We can access the properties using the dot (.) notation. The values of the variables of the person object 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 Vehicle class is defined that has the attribute brandName and the method honk().
  • Lines 9–19: A Car class is defined that inherits from Vehicle class. It has its own attributes and methods.
  • Line 17: An instance of the Car class called car is created.
  • Line 18: The display() method of the Car class is invoked.
  • Line 19: The honk() method of the Vehicle class is invoked on the car instance as the Car class inherits from the Vehicle class.

Free Resources