Swift extensions allow you to add new functionality to existing classes, structures, enumerations, or protocols without modifying the original source code. This is particularly useful when you need to enhance built-in types like String, Array, or even your custom types, making your code cleaner and more organized.
Extensions can add:
- Methods
- Computed properties
- Initializers
- Subscripts
- Nested types
- Conformance to protocols
In the following example, we declared an extension to the type Date
. So everytime we use this object on our code, we will have access to shortDate()
, instead of repeating that block of code.
When you declare an extension, you can access to the object you're extending using the keyword self
.
extension Date {
func shortDate() -> String {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
return dateFormatter.string(from: self)
}
}
var now: Date = Date()
print(now.shortDate())
Why are they useful?
Extensions improve code reusability, modularity, and allow you to extend functionality without subclassing or modifying the original implementation. They are widely used for protocol conformance, organizing related methods, or adding utilities to existing types.
Extending a Protocol
We can also create protocol extensions, so any object that adopts that protocol will get that functionality.
protocol Person {
var name: String { get }
var lastName: String { get }
}
extension Person {
var fullName: String {
return "\(name) \(lastName)"
}
}
struct Client: Person {
let name: String
let lastName: String
}
let client = Client(name: "Pablo", lastName: "Guardiola")
print(client.fullName) // Console shows: Pablo Guardiola
Extensions with Conditions
You can add conditions to an extension, so that only the variable types that meet them will get the functionality.
This is useful when we want to extend arrays.
extension Array where Element == Int {
func total() -> Int {
var result = 0
for number in self {
result += number
}
return result
}
}
var array = [1, 2, 3, 4]
print(array.total()) // Console shows: 10
Be the first to comment