Inheritance with Swift
Inheritance occurs when there is Parent — Child relationship.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Keywords comes into picture when we talk about Inheritance with swift
* override
* super
* final
Keyword “override” : Observation with keyword override.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
Keyword “super” : Observation 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”.
“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