Swift extensions allow you to add new functionality to existing types, including classes, structs, enums, and even protocols. This powerful feature helps in organizing code, promoting code reuse, and enhancing the capabilities of types without modifying their original implementation.
Let’s say we have a simple class called Rectangle
. We want to add a functionality to calculate the area of the rectangle without modifying the original class.
class Rectangle {
var width: Double
var height: Double
init(width: Double, height: Double) {
self.width = width
self.height = height
}
}
// Extending the Rectangle class to add area calculation
extension Rectangle {
func area() -> Double {
return width * height
}
}
let myRectangle = Rectangle(width: 5.0, height: 10.0)
print("Area of Rectangle: \(myRectangle.area())") // Output: Area of Rectangle: 50.0
Now, let’s extend a struct called Circle
to add a computed property for the circumference.
struct Circle {
var radius: Double
}
// Extending the Circle struct to add circumference calculation
extension Circle {
var circumference: Double {
return 2 * .pi * radius
}
}
let myCircle = Circle(radius: 4.0)
print("Circumference of Circle: \(myCircle.circumference)") // Output: Circumference of Circle: 25.1327412287191
You can also extend protocols to provide default implementations for specific functionalities. Here’s an example with a protocol called Describable
.
protocol Describable {
func describe() -> String
}
// Extending the Describable protocol to provide a default implementation
extension Describable {
func describe() -> String {
return "This is a describable object."
}
}
class Person: Describable {
var name: String
init(name: String) {
self.name = name
}
}
let person = Person(name: "Alice")
print(person.describe()) // Output: This is a describable object.
Swift extensions are a powerful and flexible way to enhance the functionality of your existing types. By using extensions, you can keep your code organized and maintainable while adding new features seamlessly. Start using extensions in your Swift projects to improve code clarity and reusability!