Concept Flow - Extension syntax
Start
Define Extension
Add new properties or methods
Use extended type with new features
End
The flow shows defining an extension, adding new features, then using them with the original type.
extension Int { func squared() -> Int { return self * self } } let num = 4 print(num.squared())
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define extension on Int adding method squared() | Extension added | Int now has squared() method |
| 2 | Create constant num with value 4 | num = 4 | num stores 4 |
| 3 | Call num.squared() | 4 * 4 | 16 |
| 4 | Print result of num.squared() | print(16) | Output: 16 |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| num | undefined | 4 | 4 | 4 |
Extension syntax in Swift:
- Use 'extension TypeName { }' to add new methods or computed properties.
- Cannot add stored properties.
- Extended features are available on all instances of the type.
- Useful to add functionality without subclassing or modifying original code.