Swift Introduction | Protocols and Extensions | Extensions
A protocol requires a class to implement methods. An extension adds methods directly to an existing class. Its syntax is simple.
extension ClassName {
...... additions ......
}
Specify the class to extend as ClassName.
You can add properties as well as methods. However, an extension can add only computed properties, which define get and set behavior.
Extensions work with your own classes, classes provided by the Swift standard library, and classes from iOS frameworks.
For example, extend Int with a getTotal method that calculates the sum from 1 through a given number.
extension Int {
func getTotal()->Int {
var total:Int = 0
for i in 1...self {
total += i
}
return total
}
}
var num = 1234
print(num.getTotal())
The declaration extension Int extends the Int type. Every Int value can then use the getTotal method. Even an ordinary variable such as var num = 1234 can call it. To calculate the sum through 100, call 100.getTotal().
Extensions make it easy to add functionality even to fundamental Swift types such as Int and String.