0
0
Swiftprogramming~10 mins

Extension syntax in Swift - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Swift
extension Int {
    func squared() -> Int {
        return self * self
    }
}

let num = 4
print(num.squared())
This code adds a new method 'squared' to Int and uses it to print 16.
Execution Table
StepActionEvaluationResult
1Define extension on Int adding method squared()Extension addedInt now has squared() method
2Create constant num with value 4num = 4num stores 4
3Call num.squared()4 * 416
4Print result of num.squared()print(16)Output: 16
💡 Execution ends after printing the squared value of num
Variable Tracker
VariableStartAfter Step 2After Step 3Final
numundefined444
Key Moments - 2 Insights
Can extensions add stored properties to a type?
No, extensions in Swift cannot add stored properties, only computed properties or methods. This is shown in Step 1 where only a method is added.
Does the original Int type change permanently after extension?
Yes, after defining the extension (Step 1), all Int values can use the new method, as seen in Step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at Step 4?
A4
B16
C8
DError
💡 Hint
Check the 'Result' column in Step 4 of the execution_table.
At which step is the method 'squared()' added to Int?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column describing extension definition.
If we tried to add a stored property in the extension, what would happen?
AIt would compile and work normally
BIt would add the property only to new instances
CIt would cause a compile-time error
DIt would add the property only to existing instances
💡 Hint
Refer to the key moment about stored properties in extensions.
Concept Snapshot
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.
Full Transcript
This visual trace shows how Swift extensions work. First, an extension is defined on Int to add a method called squared(). Then, a constant num is created with value 4. Calling num.squared() multiplies 4 by itself and returns 16. Finally, printing the result outputs 16. Extensions add new methods or computed properties but cannot add stored properties. Once defined, all Int values can use the new method.