C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Self: The self-reference in an extension method accesses the instance we are calling the extension method on.
MiddleChar: This method loops forward from startIndex, and backward from endIndex, to return the middle Character from a String.
StringendIndexSwift program that uses extension method
extension String {
func middleChar() -> Character {
// Get middle char from a String.
var a = self.startIndex
var b = self.endIndex.predecessor()
while true {
if a >= b {
return self[a]
}
a = a.successor()
b = b.predecessor()
}
}
}
// 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)
Output
b
i
a
AddTen: 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.
Swift program that uses extension, mutating func
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)
Output
210
220