Swift Base Class
A class that does not inherit any methods, attributes, or functions from other classes is called Base class.
Example
class StudentDetails {
var stname: String!
var marks1: Int!
var marks2: Int!
var marks3: Int!
init(stname: String, marks1: Int, marks2: Int, marks3: Int) {
self.stname = stname
self.marks1 = marks1
self.marks2 = marks2
self.marks3 = marks3
}
}
let stname = "Abhishek"
let marks1 = 60
let marks2 = 85
let marks3 = 89
print(stname)
print(marks1)
print(marks2)
print(marks3)
Output
Abhishek
60
85
89
StudentDetails is defined as a base class that contains the student's name as well as three subjects marked as mark1, mark2, and mark3. The value for the base class is initialized using the 'let' keyword, and the value is shown using the 'print' function.
Subclass
The subclass inherits the base class's attributes, methods, and functions. The prefix ':' is used before the base class name to define a subclass.
Example
class Person {
var firstName: String
var lastName: String
let birthPlace: String
init(birthPlace: String) {
self.birthPlace = birthPlace
}
}
class Student: Person
{
var school: String
}
let student = Student(birthPlace: "US")
student.lastName = "Scoot"
student.firstName = "Travis"
print(student.birthPlace)
print(student.firstName)
print(student.lastName)
Output
US
Travis
Scott
Overriding
A subclass can implement an instance method, type method, instance property, type property, or subscript that it would otherwise inherit from a superclass in its own way. Overriding is the term for this.
Prefix your overriding definition with the override keyword to override a characteristic that would otherwise be inherited. This ensures that you mean to give an override and haven't accidentally provided a matched definition. Any overrides lacking the override keyword are diagnosed as an error when your code is generated, and they can cause unexpected behaviour.
The override keyword also tells the Swift compiler to look for a declaration that matches the one you gave for the override in your overriding class's superclass (or one of its parents). This check confirms the accuracy of your overriding definition.
Swift Method Overriding
We've seen how a base class's inheritance method is inherited by its subclass and used by subclass instances. However, for the same method provided in the base class, we may wish an instance to reply differently. Method overriding can be used to do this. Method overriding allows us to specify a method with the same name, parameter list, and return type as a subclass. The method defined in the subclass is then invoked instead of the one declared in the base class when that method is called.
The "override" keyword, followed by a method declaration with the same name, parameter list, and return type as the base class, can be used to override base class methods in Swift.
Example
class employee {
func sayHello(){
print("Hello from employee.")
}
}
class manager : employee {
override func sayHello(){
print("Hello from manager.")
}
}
class engineer : employee {
override func sayHello(){
print("Hello from engineer.")
}
}
let emp = employee()
let mng = manager()
let eng = engineer()
emp.sayHello();
mng.sayHello();
eng.sayHello();
Output
Hello from employee.
Hello from manager.
Hello from engineer.
Property Overriding
You can give your own custom getter and setter for an inherited instance or class property, as well as add property observers to allow the overriding property to detect changes in the underlying property value.
Overriding Property Getters and Setters
In Swift 4, the user can supply custom getters and setters to override inherited properties, whether they are stored or computed. The inherited property name and type are unknown to the subclass. As a result, the user must declare the name and type of the overriding property defined in the superclass in the subclass.
This can be accomplished in two ways:
- When a setter is specified for an overriding property, the user must also specify a getter.
- When we don't want to change the inherited property getter, we may simply use the syntax 'super.someProperty' to transfer the inherited value to the superclass.
class Circle {
var radius = 10.5
var area: String {
return "of rectangle for \(radius) "
}
}
class Rectangle: Circle {
var print = 9
override var area: String {
return super.area + " is now overridden as \(print)"
}
}
let rect = Rectangle()
rect.radius = 24.0
rect.print = 5
print("Radius \(rect.area)")
Output
Radius of rectangle for 24.0 is now overridden as 5
Overriding Property Observers
The idea of 'property overriding' is introduced in Swift 4 when a new property needs to be added for an inherited property. When the value of inherited property is changed, the user is notified. Inherited constant stored properties and inherited read-only calculated properties, however, are not overridable.
Example
class Circle {
var radius = 12.5
var area: String {
return "of rectangle for \(radius) "
}
}
class Rectangle: Circle {
var print = 7
override var area: String {
return super.area + " is now overridden as \(print)"
}
}
let rect = Rectangle()
rect.radius = 24.0
rect.print = 5
print("Radius \(rect.area)")
class Square: Rectangle {
override var radius: Double {
didSet {
print = Int(radius/5.0)+1
}
}
}
let sq = Square()
sq.radius = 100.0
print("Radius \(sq.area)")
Output
Radius of rectangle for 24.0 is now overridden as 5
Radius of rectangle for 100.0 is now overridden as 21
Benefits of Inheritance
- Inheritance encourages reuse. When a class inherits or derives from another class, it gains access to all of the inherited class's capabilities.
- Reusability improved dependability. The code for the base class will already be tested and debugged.
- Because existing code is reused, development and maintenance costs are reduced.
- Subclasses inherit a common interface thanks to inheritance.
- Inheritance reduces code repetition while also allowing for code extension.
Frequently Asked Questions
Is swift a procedural language or an object-oriented language?
Swift is an inherited language from C and Objective-C that may be used as a procedural or object-oriented language. Class is an object-oriented programming language notion.
Is Swift frontend or backend?
We can use Swift to build software that runs on the client (frontend) and the server (backend).
What is Swift most commonly used for?
Swift is an Apple-developed programming language for developing programs for iOS, Mac, Apple TV, and Apple Watch. It's intended to allow developers more flexibility than ever before. Swift is simple to use and open-source, allowing anyone with an idea to make something amazing.
What is Dictionary in Swift?
The key-value pairs are stored in Swift Dictionary, and the value is accessed by using the key. In other programming languages, hash tables are similar.
In Swift, what are the various control transfer statements?
The control transfer statements in Swift are as follows:
- Continue
- Break
- Fallthrough
- Return
Conclusion
In this article, we have extensively discussed Swift inheritance.
We hope that this blog has provided you with new information. And if you're interested in learning more, see our posts on Object-Oriented Programming, Classes and Objects, Byte Class in Java, Character Class in Java, Best DevOps Tools To Get Acquainted With. Please vote for our blog to help other ninjas succeed.
Visit our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!
Happy Reading!