Ad space (banner)
๐ŸฆSwift Lessons
Lesson 16 / 68

Inheritance (Extending a Class)

In this lesson you will learn how to extend a class through inheritance in Swift, so classes that share characteristics can reuse code. This is for anyone searching for "Swift inheritance how to use".

You inherit with class Child: Parent, and override replaces a method from the parent. Gathering the shared parts into a parent class saves you writing the same code repeatedly.

The sample code makes Animal the parent, has Dog inherit from it with : Animal, and replaces the parent's method with override func speak(). The key point is that you keep the parent's functionality and change only the parts you need.

A common stumbling block for beginners is forgetting override. Writing a method with the same name as the parent's without it is a compile error - you have to state explicitly that the override is deliberate.

In real-world development, the final keyword is also widely used to stop a class or method from being inherited or overridden any further.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)