Swift Extensions in Depth
An extension adds new behaviour to an existing type without changing its original declaration. The new members can then be used on every value of that type.
A computed property for Int
The extension adds a squared property to Int. The property multiplies the number by itself, so the number 7 prints 49.
extension Int {
var squared: Int {
return self * self
}
}
let number = 7
print(number.squared)A method for Int
The extension adds a repeatPrint method to Int. The number says how many times the line prints, so the line appears three times.
extension Int {
func repeatPrint(_ text: String) {
for _ in 0..<self {
print(text)
}
}
}
let count = 3
count.repeatPrint("Keep going")A method for String
The extension adds a shout method to String. The method returns the text in uppercase letters with an exclamation mark added.
extension String {
func shout() -> String {
return self.uppercased() + "!"
}
}
let word = "hello"
print(word.shout())Extending a struct from the same program
The Book struct is declared first with two stored properties. Its extension sits in a separate block and adds the summary method.
struct Book {
var title: String
var pages: Int
}
extension Book {
func summary() -> String {
return "\(title) has \(pages) pages"
}
}
let book = Book(title: "Field Notes", pages: 120)
print(book.summary())Example
extension String {
func bracketed() -> String {
return "[" + self + "]"
}
}
let label = "ready"
print(label.bracketed())
print(label.count)Key points
- An extension is written with the extension keyword, the type name, and a block of new members.
- An extension can add a computed property that builds its value from the value itself.
- An extension can add a method that every value of the type can call.
- A type written in the same program can be extended in a separate block from its own declaration.
- An extension cannot add a stored property, because a stored property needs storage inside every value.
In this example, the String extension adds a bracketed method that wraps the text in square brackets. The first print shows [ready] for the word ready. The second print shows 5, the count of letters that was already part of String.
Note
Existing values of the type gain the new members with no change to how they are made.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which of these can an extension add to a type?