0
0
Swiftprogramming~5 mins

Extending built-in types in Swift

Choose your learning style9 modes available
Introduction
Extending built-in types lets you add new features to existing types, like numbers or strings, without changing their original code.
You want to add a new function to a number or string to make your code simpler.
You need to add a property to a built-in type to store extra information.
You want to organize your code by grouping related functions with the type they work on.
You want to add convenience methods to types like Int, String, or Array to reuse often.
Syntax
Swift
extension TypeName {
    // new methods or computed properties
}
You cannot add stored properties in extensions, only computed properties or methods.
Extensions help keep your code clean by adding features without subclassing.
Examples
Adds a method to Int that returns the number multiplied by itself.
Swift
extension Int {
    func squared() -> Int {
        return self * self
    }
}
Adds a computed property to String that returns the reversed version.
Swift
extension String {
    var reversedString: String {
        return String(self.reversed())
    }
}
Sample Program
This program adds a squared() method to Int and uses it to print the square of 5.
Swift
extension Int {
    func squared() -> Int {
        return self * self
    }
}

let number = 5
print("The square of \(number) is \(number.squared())")
OutputSuccess
Important Notes
Extensions cannot add stored properties, only computed properties or methods.
Use extensions to add functionality to types you do not own or cannot change.
Extensions can also add initializers, subscripts, and conform to protocols.
Summary
Extensions let you add new methods or computed properties to existing types.
You cannot add stored properties in extensions.
They help keep code organized and reusable without subclassing.