Extensions add new functionality to an existing class, structure, enumeration, or protocol type.
This includes the ability to extend types for which you do not have access to the original source code!
Extensions are incredibly useful for organizing code and keeping your base objects clean and focused.
You can use an extension to add custom methods or computed properties to Apple's built-in types, such as Int, String, or Double.
You declare an extension using the extension keyword.
extension Int {
// Adding a computed property to Int
var squared: Int {
return self * self
}
}
let number = 5
print(number.squared) // Outputs 25
Because of the extension, every single Integer in your entire project now has a .squared property!
Extensions can also add new instance methods and type methods to existing types.
extension String {
func shout() {
print("\(self.uppercased())!!!")
}
}
let greeting = "hello"
greeting.shout()
A very common and highly recommended pattern in Swift development is to use extensions to group related functionality together.
Instead of cluttering a single Class definition with dozens of methods, you can split logical chunks into separate extensions.
This is especially useful when conforming to multiple protocols.
struct User {
var name: String
}
// We use an extension strictly to handle protocol conformance!
extension User: CustomStringConvertible {
var description: String {
return "User(name: \(name))"
}
}
let admin = User(name: "Akash")
print(admin)
It is important to note that extensions cannot add new stored properties (variables) to a type. They can only add computed properties.
Can an extension add new stored properties (like `var count = 0`) to an existing Swift struct?