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.extension in Swift?String type in Swift?extension followed by the type name without parentheses or brackets.extension String { } uses correct syntax. extend String { } uses invalid keyword. extension String() { } adds invalid parentheses. extension String[] { } uses invalid array notation.extension Int {
func squared() -> Int {
return self * self
}
}
let number = 4
print(number.squared())squared() to Int that returns the number multiplied by itself.4.squared() returns 4 * 4 = 16.extension Double {
func half() -> Double {
self / 2
}
}return keyword.isEven to Int using an extension that returns true if the number is even, otherwise false. Which code correctly implements this?var with a getter. extension Int { var isEven: Bool { self % 2 == 0 } } uses correct concise syntax; the func version declares a method, the if version lacks an else branch causing compile error, the division version has wrong logic.extension Int { var isEven: Bool { self % 2 == 0 } } uses concise expression self % 2 == 0 which returns true if even. extension Int { var isEven: Bool { if self % 2 == 0 { return true } } } omits else branch, causing compiler error. extension Int { var isEven: Bool { self / 2 == 0 } } incorrectly uses division instead of modulo.num.isEven(). Incomplete if fails to compile. Division fails for even numbers like 2 (2/2 == 1 != 0).Pass the test and this pattern moves unknown