Extensions in Swift
<p>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.</p>
<p><em>This post was originally posted at </em><a href="https://mahigarg.github.io/blogs/extensions-in-swift/" rel="noopener ugc nofollow" target="_blank">https://mahigarg.github.io/blogs/extensions-in-swift/</a> <em>and later reposted on Medium.</em></p>
<h1>Extending Classes in Swift</h1>
<p>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 <code><em>Person</em></code> class:</p>
<pre>
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!"</pre>
<p>By using extensions, we separate the core functionality of the Person class from additional features like sayHello(), enhancing code organization and maintainability.</p>
<p><a href="https://medium.com/@mahigarg/extensions-in-swift-a1373b00bf8a">Visit Now</a></p>