Home
Swift
extension Methods
Updated Aug 23, 2023
Dot Net Perls
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.
String Length
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 23, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen