Inheritance with Swift

Roshan Kumar Sah
Dev Genius
Published in
3 min readOct 18, 2020

--

Inheritance: Inheritance is the mechanism of basing an object or class upon another object (prototype-based inheritance) or class (class-based inheritance), retaining similar implementation.

Inheritance occurs when there is Parent — Child relationship.

Inheritance

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Keywords comes into picture when we talk about Inheritance with swift
* override
* super
* final

Keyword “override” : Observation with keyword override.

Override with function
Override with property

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

Keyword “super” : Observation with keyword “super”.

Override with keyword `super`

Some rules associated with overriding property are
1. Overriding property with getter can be getter.
2. Overriding property with getter can be getter and setter. vice versa is not true.

— — — — — - — — — — — — — — — — — — — — — — — — — — — — — — —

Keyword “final” : Observation with keyword “final”.

Preventing override with final

“final” keyword prevent from being overriden.
This keyword can be used with folllowing keywords.
1. class
2. func
3. var
4. subscripts
5. class func.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

Try out questions
Question 1. What it will print or Compile time waring
class Foo {
func foo() {print(“I’m from Foo”)}
}
class Bar: Foo {}let instanceOfBar = Bar()
instanceOfBar.foo()
Question 2. What it will print or Compile time waring
class Foo {
final func foo() {print(“I’m from Foo”)}
}
class Bar: Foo {}let instanceOfBar = Bar()
instanceOfBar.foo()
Question 3. What it will print or Compile time waring
class Foo {
final func foo() {print(“I’m from Foo”)}
}
class Bar: Foo {
func foo() {print(“I’m from Bar”)}
}
let instanceOfBar = Bar()
instanceOfBar.foo()
Question 4. What it will print or Compile time waring
class Foo {
final class func foo() {print(“I’m from Foo”)}
}
class Bar: Foo {}let instanceOfBar = Bar()
instanceOfBar.foo()
Try finding reason behind each behaviour. Its fun. 🤪

— — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Next chapter is about Initialization.

Further reading:
https://docs.swift.org/swift-book/LanguageGuide/Inheritance.html

You can reach me out here
roshankumar350@gmail.com

--

--