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&nbsp;</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>&nbsp;<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&rsquo;s consider a simple example of extending a&nbsp;<code><em>Person</em></code>&nbsp;class:</p> <pre> class Person { var name: String init(name: String) { self.name = name } } extension Person { func sayHello() { print(&quot;Hello, my name is \(name)!&quot;) } } // Usage let person = Person(name: &quot;Mahi&quot;) person.sayHello() // Output: &quot;Hello, my name is Mahi!&quot;</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>