Classes are reference types used to define reusable and flexible blueprints for objects. Classes can have properties, methods, initialisers, deinitialisers and can conform to protocols. They also support inheritance, which makes them powerful for building complex systems.
Characteristic of Class
- Reference Type: Instances are passed by reference, meaning multiple variables can point to the same instance.
- Inheritance: Classes can inherit properties and methods from other classes.
- Deinitialisers: Classes can define deinitialisers (
deinit
) to release resources. - Mutable Properties: Properties of a class instance can be modified, even if the instance is declared with
let
. - Protocols and Extensions: Classes can adopt protocols and be extended.
class Person {
var name: String
init(name: String) {
self.name = name
}
func description() -> String {
return "\(name)"
}
}
// Create an instance
let person = Person(name: "Bishal")
print(person.description()) // Output: Bishal
Initialiser(Constructor)
Classes can have multiple initialisers, and these can be overridden in subclasses
class Rectangle {
var width: Double
var height: Double
init(width: Double, height: Double) {
self.width = width
self.height = height
}
convenience init(side: Double) {
self.init(width: side, height: side)
}
}
let square = Rectangle(side: 5.0)
print("Square: \(square.width) x \(square.height)") // Output: Square: 5.0 x 5.0
Deinitialisers
Deinitialisers are used to perform cleanup when a class instance is deallocated
class FileManager {
var fileName: String
init(fileName: String) {
self.fileName = fileName
print("\(fileName) opened.")
}
deinit {
print("\(fileName) closed.")
}
}
var file: FileManager? = FileManager(fileName: "data.txt")
file = nil // Output: data.txt closed.
Class as Reference Type
// Define a class
class PersonClass {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
var classPerson1 = PersonClass(name: "Ram", age: 20)
var classPerson2 = classPerson1 // References the same instance
// Modify classPerson2
classPerson2.name = "Shyam"
print("Class Person 1: \(classPerson1.name), Age: \(classPerson1.age)") // Shyam, 20
print("Class Person 2: \(classPerson2.name), Age: \(classPerson2.age)") // Shyam, 20
When we assign classPerson1
to classPerson2
, both variables reference the same instance. Changes made to classPerson2
are reflected in classPerson1