Extension. A class or struct contains many useful funcs. But sometimes this is not enough. An additional method is needed. An extension method can solve this problem.
With the extension keyword, we add new methods to existing types like String or Int. A program might need to add 10 to a number. We can insert an addTen method to Int.
String extension. Let us begin with a String extension method. We use an "extension String" block. We introduce "middleChar() which" returns a character.
Note The self-reference in an extension method accesses the instance we are calling the extension method on.
Note 2 MiddleChar loops forward from startIndex, and backward from endIndex, to return the middle Character from a String.
extension String {
func middleChar() -> Character {
// Get middle char from a String.
var a = self.startIndex
var b = self.index(self.endIndex, offsetBy: -1)
while true {
if a >= b {
return self[a]
}
a = self.index(a, offsetBy: 1)
b = self.index(b, offsetBy: -1)
}
}
}
// Test our string extension method.
let letters = "abc"
let middle1 = letters.middleChar()
print(middle1)
let shirt = "shirt"
let middle2 = shirt.middleChar()
print(middle2)
let leaf = "leaf"
let middle3 = leaf.middleChar()
print(middle3)b
i
a
Mutating, Int. An extension method can change the underlying object. We use the mutating keyword to indicate the "self" reference is being changed. This allows us to change an Int value.
Info We implement this func as an Int extension. The Int value is changed when addTen() executes.
Note Mutating methods sometimes make more sense. But often just creating a new instance and returning it is sufficient.
extension Int {
mutating func addTen() {
// Change value of self in mutating func.
self += 10
}
}
var number = 200
// Test addTen method.
number.addTen()
print(number)
number.addTen()
print(number)210
220
A review. Extension methods are powerful. They allow us to decorate existing types with additional, customized, specific methods. We compose programs that are clearer and easier to read.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 23, 2023 (edit).