Extensions in Swift allow developers to add new functionality to existing classes and protocols without modifying their original implementation. For classes, extensions can include new methods, computed properties, and initializers, promoting code modularity. For protocols, extensions can provide default implementations for methods, enhancing code adaptability. By separating concerns through extensions, developers can achieve cleaner, more organized code, increasing code reusability and maintainability in Swift projects.
This post was originally posted at https://mahigarg.github.io/blogs/extensions-in-swift/ and later reposted on Medium.
Extending Classes in Swift
Swift enables developers to extend classes with new methods, computed properties, and initializers, providing a modular way to add functionality. Let’s consider a simple example of extending a Person class:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
extension Person {
func sayHello() {
print("Hello, my name is \(name)!")
}
}
// Usage
let person = Person(name: "Mahi")
person.sayHello() // Output: "Hello, my name is Mahi!"
By using extensions, we separate the core functionality of the Person class from additional features like sayHello(), enhancing code organization and maintainability.