0
0
Swiftprogramming~5 mins

Extension syntax in Swift

Choose your learning style9 modes available
Introduction
Extensions let you add new features to existing types without changing their original code. This helps keep your code organized and easy to update.
You want to add a new function to a type you did not create, like String or Int.
You want to group related functions together to keep your code clean.
You want to add computed properties to a type without subclassing.
You want to make an existing type conform to a protocol.
You want to add convenience initializers to a type.
Syntax
Swift
extension TypeName {
    // new functionality here
}
Replace TypeName with the name of the type you want to extend.
You can add methods, computed properties, initializers, and make the type conform to protocols.
Examples
Adds a method squared() to the Int type that returns the number multiplied by itself.
Swift
extension Int {
    func squared() -> Int {
        return self * self
    }
}
Adds a computed property reversedString to String that returns the reversed version of the string.
Swift
extension String {
    var reversedString: String {
        return String(self.reversed())
    }
}
Makes Double conform to the CustomStringConvertible protocol by adding a description property.
Swift
extension Double: CustomStringConvertible {
    var description: String {
        return "Value: \(self)"
    }
}
Sample Program
This program adds a new method squared() to the Int type. It then uses this method on the number 5 and prints the result.
Swift
extension Int {
    func squared() -> Int {
        return self * self
    }
}

let number = 5
print("\(number) squared is \(number.squared())")
OutputSuccess
Important Notes
Extensions cannot add stored properties to types, only computed properties or methods.
You can use extensions to organize your code better by grouping related functionality.
Extensions work with classes, structs, enums, and protocols.
Summary
Extensions add new features to existing types without changing their original code.
You can add methods, computed properties, initializers, and protocol conformance.
Extensions help keep your code clean and organized.