Extensions let you add new features to existing code without changing the original code. This keeps your code safe and organized.
0
0
Why extensions add capability without modifying in Swift
Introduction
You want to add new functions to a class from a library you can't change.
You want to keep your code clean by grouping related functions separately.
You want to add features to a type without creating a new subclass.
You want to add helper methods to built-in types like String or Int.
You want to organize your code better by splitting big classes into smaller parts.
Syntax
Swift
extension TypeName { // new methods or properties }
Use extension keyword followed by the type name.
You cannot add stored properties with extensions, only computed properties and methods.
Examples
Adds a new method
shout() to the String type that returns the string in uppercase with an exclamation mark.Swift
extension String { func shout() -> String { return self.uppercased() + "!" } }
Adds a computed property
isEven to Int to check if a number is even.Swift
extension Int { var isEven: Bool { return self % 2 == 0 } }
Sample Program
This program adds a new method squared() to the Double type using an extension. It then prints the square of 3.0.
Swift
extension Double { func squared() -> Double { return self * self } } let number = 3.0 print("The square of \(number) is \(number.squared())")
OutputSuccess
Important Notes
Extensions cannot add stored properties, only computed properties and methods.
Extensions help keep your code modular and easier to maintain.
They allow you to add functionality to types you do not own, like system types.
Summary
Extensions add new features without changing original code.
They keep code safe and organized.
Useful for adding methods or computed properties to existing types.