What is Swift Inheritance and Polymorphism?


What is Swift Inheritance and Polymorphism?

In Swift programming language, inheritance and polymorphism are among the cornerstones of object-oriented programming. Inheritance allows a class to take on the properties and methods of another class, while polymorphism enables different objects that share the same interface or base class to perform their own specific behaviors. In this article, we will examine "what is Swift inheritance and polymorphism", how it is used, and how it functions with code examples.

How Does Inheritance Work in Swift?

Inheritance prevents code repetition and allows you to gather common code in one place. In Swift, classes can inherit from another class. All the properties and functions of the "base" or parent class are passed to the "subclass", and they can be modified (overridden) if desired.

Inheritance Example with Swift


class Animal {
    var name: String
    init(name: String) {
        self.name = name
    }
    func makeSound() {
        print("
<Animal> sound  AA")
    }
}

class Cat: Animal {
    override func makeSound() {
        print("
Meow! My name is \(name)")
    }
}

let tekir = Cat(name: "Tekir")
tekir.makeSound() // "Meow! My name is Tekir"

Polymorphism: Practical Use

With polymorphism, you can manage different subclass objects using a reference of the base type and call their behaviors. This makes your code flexible and makes type-independent operations easier. Especially in collections and function parameters, polymorphism is a very powerful tool.

Functional Use with Polymorphism


let animals: [Animal] = [Animal(name: "Living"), Cat(name: "Minnak")]
for animal in animals {
    animal.makeSound()
}
// "<Animal> sound " and "Meow! My name is Minnak" are printed

Conclusion and Further Reading

The answer to the question "what is Swift inheritance and polymorphism" is important for developing more sustainable, maintainable, and powerful software. Thanks to inheritance, common functions are not rewritten; with polymorphism, the flexibility of the code increases. To learn more about Swift and object-oriented programming, you can check the official Swift documentation.