Extensions in Swift allow you to add new functionality to existing classes, structures, enumerations, or protocols. They provide a way to extend the behavior of types without subclassing. This can be especially useful for adding methods, properties, initializers, and nested types to existing types.
Here is an example of how you can use extensions to add a computed property to a Swift structure:
struct Person {
var firstName: String
var lastName: String
}
extension Person {
var fullName: String {
return "\(firstName) \(lastName)"
}
}
In the above code snippet, we have defined a simple structure Person
with properties firstName
and lastName
. We then use an extension to add a computed property fullName
that concatenates the first and last names.
Extensions can help you keep your code organized by grouping related functionality together. They also provide a way to add functionality to types that you do not have access to the original source code for, such as built-in Swift types or third-party libraries.
Extensions can also be used to provide default implementations for methods in protocols. This can be helpful when conforming types to protocols but want to implement only specific methods.
protocol Vehicle {
func start()
func stop()
}
extension Vehicle {
func stop() {
print("Vehicle has stopped")
}
}
In this example, the Vehicle
protocol has two methods start()
and stop()
. We use an extension to provide a default implementation for the stop()
method, allowing conforming types to only implement the start()
method if needed.
Extensions are a powerful feature in Swift that can help you enhance and customize your code. By using extensions, you can improve the readability, maintainability, and extensibility of your Swift code.