Call a function from another class in Swift

In this tutorial, we will create two classes and try to call a function from Class 1 in Class 2. This helps in various tasks of classes and their objects.

We will create a class named Vehicles with a function name as CarName which takes a String and prints a String. Another class name is Car where we have created a function named whichCar. Also, an object is created of the class Vehicle and a variable is declared by the CarName as Brezza. Then in that class Car, the function of the Vehicle is called with the variable of CarName.

At last, the function whichCar() of Car() is called and we get the desired output as:

class Vehicle {

    func CarName(name: String) -> String {
        return ("This Vehicle: \(name)")
    }
}


class Car {

    func whichCar() {
        let ob=Vehicle()
        let CarName = "Brezza"

        print(ob.CarName(name: CarName));
    }
}
Car().whichCar();
Output-This Vehicle: Brezza

Here the flow of the program is

  1. A class named Vehicle is created.
  2. CarName() function is created inside Vehicle.
  3. A class named Car is created.
  4. Function whichCar() is defined
  5. An object of a Vehicle is created.
  6. Variable is created with CarName as “Brezza”.
  7. This variable is passed to function using the object of the Vehicle.
  8. whichCar() function is called from class Car.

When whichCar() function is called, which contains an object of Vehicle class and a variable name CarName as Brezza. After then, the CarName function is called using the object of the Vehicle class and it returns This Vehicle: Brezza as Output which appears on the screen.

Leave a Reply

Your email address will not be published. Required fields are marked *