Classes,Properties and Methods in Swift

Inheritance, Polymorphism & Protocols in Swift

In this unit, we will delve into the concepts of inheritance, polymorphism, and protocols in Swift. These are fundamental concepts in object-oriented programming and are crucial for creating complex and flexible code structures.

Inheritance

Inheritance is a fundamental concept in object-oriented programming. It allows one class to inherit the properties and methods of another class. In Swift, a class can inherit from any other class, and it can also override the methods and properties it inherits.

Here is a basic example of inheritance in Swift:

class Vehicle { var speed: Double = 0.0 func makeNoise() { // do nothing - an arbitrary vehicle doesn't necessarily make a noise } } class Car: Vehicle { var gear: Int = 1 override func makeNoise() { print("Vroom!") } }

In this example, Car is a subclass of Vehicle and inherits its speed property and makeNoise() method. It also overrides the makeNoise() method to provide its own implementation.

Polymorphism

Polymorphism is another fundamental concept in object-oriented programming. It allows a subclass to be treated as its superclass. This is particularly useful when you want to work with a collection of different objects in a uniform way.

Here is an example of polymorphism in Swift:

let car: Vehicle = Car() car.makeNoise() // Prints "Vroom!"

In this example, even though car is declared as a Vehicle, it's actually a Car, so it uses the Car version of the makeNoise() method.

Protocols

Protocols are a way of defining a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. Protocols can be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.

Here is an example of a protocol in Swift:

protocol Movable { var speed: Double { get } func move() } class Vehicle: Movable { var speed: Double = 0.0 func move() { print("Moving at \(speed) miles per hour") } }

In this example, Vehicle adopts the Movable protocol and provides an implementation for its speed property and move() method.

By the end of this unit, you should have a solid understanding of how to use inheritance, polymorphism, and protocols in Swift to create more complex and flexible code structures.