Bird
Raised Fist0
Swiftprogramming~10 mins

Extending built-in types in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Extending built-in types
Start
↓
Define Extension
↓
Add new method/property
↓
Use extended type
↓
Call new method/property
↓
Get result
↓
End
You start by defining an extension to a built-in type, add new methods or properties, then use the extended type to call those new features.
Execution Sample
Swift
extension Int {
    func squared() -> Int {
        return self * self
    }
}

let number = 5
print(number.squared())
This code adds a new method 'squared' to Int that returns the number multiplied by itself, then prints 25.
Execution Table
StepActionEvaluationResult
1Define extension Int with method squared()Extension createdInt now has squared() method
2Create constant number = 5number assigned 5number = 5
3Call number.squared()Calculate 5 * 525
4Print resultOutput 25Console shows 25
💡 Program ends after printing the squared value
Variable Tracker
VariableStartAfter Step 2After Step 3Final
numberundefined555
result of squared()undefinedundefined2525
Key Moments - 2 Insights
Why can we call squared() on an Int even though Int doesn't have it originally?
Because the extension adds the squared() method to Int before we call it, as shown in step 1 of the execution_table.
Does the original Int type change permanently after extension?
No, extensions add functionality only in the current scope or module; the original Int type remains unchanged elsewhere.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'number' after step 2?
Aundefined
B25
C5
D0
💡 Hint
Check the 'variable_tracker' table under 'number' after Step 2
At which step is the squared() method actually called?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in the execution_table for when number.squared() is called
If we changed number to 3, what would be the output at step 4?
A6
B9
C3
D25
💡 Hint
Recall squared() returns number * number; see execution_table step 3 for calculation
Concept Snapshot
Swift extensions let you add new methods or properties to existing types.
Syntax: extension TypeName { func newMethod() { } }
You can call new methods on instances as if built-in.
Extensions do not modify original type permanently.
Useful to add functionality without subclassing.
Full Transcript
This example shows how to extend Swift's built-in Int type by adding a new method called squared(). The extension is defined first, adding the method that returns the number multiplied by itself. Then, a constant number is created with value 5. Calling number.squared() runs the new method, calculating 25. Finally, the result 25 is printed to the console. The execution table traces each step: defining the extension, creating the number, calling squared(), and printing the result. The variable tracker shows how 'number' stays 5 and the squared() result is 25. Key moments clarify that extensions add methods to types so you can call them like built-in methods, but the original type is not permanently changed. The quiz tests understanding of variable values and method calls during execution. The snapshot summarizes how extensions work in Swift simply and clearly.

Practice

(1/5)
1. What is the main purpose of extending built-in types in Swift?
easy
A. To change the stored properties of existing types
B. To delete existing methods from built-in types
C. To add new methods or computed properties to existing types
D. To create subclasses of built-in types

Solution

  1. Step 1: Understand what extensions do

    Extensions allow adding new methods or computed properties to existing types without subclassing.
  2. Step 2: Identify what extensions cannot do

    Extensions cannot add stored properties or delete existing methods.
  3. Final Answer:

    To add new methods or computed properties to existing types -> Option C
  4. Quick Check:

    Extensions add methods/properties = B [OK]
Hint: Remember: extensions add features, not stored data [OK]
Common Mistakes:
  • Thinking extensions can add stored properties
  • Confusing extensions with subclassing
  • Believing extensions can remove methods
2. Which of the following is the correct syntax to extend the built-in Int type with a method isEven() that returns a Bool?
easy
A. extension Int { func isEven() -> Bool { return self % 2 == 0 } }
B. extend Int { func isEven() -> Bool { return self % 2 == 0 } }
C. extension Int { func isEven { return self % 2 == 0 } }
D. extension Int { isEven() -> Bool { return self % 2 == 0 } }

Solution

  1. Step 1: Identify the correct keyword for extension

    Swift uses the keyword extension to add methods to existing types.
  2. Step 2: Check method syntax

    The method must have parentheses and a return type: func isEven() -> Bool. The body uses self % 2 == 0.
  3. Final Answer:

    extension Int { func isEven() -> Bool { return self % 2 == 0 } } -> Option A
  4. Quick Check:

    Correct extension syntax = D [OK]
Hint: Use 'extension' keyword and full method signature [OK]
Common Mistakes:
  • Using 'extend' instead of 'extension'
  • Omitting parentheses in method declaration
  • Missing 'func' keyword before method name
3. Consider this Swift code:
extension String {
    func reversedString() -> String {
        return String(self.reversed())
    }
}

let word = "hello"
print(word.reversedString())

What is the output when this code runs?
medium
A. Error: reversed() not found
B. hello
C. nil
D. olleh

Solution

  1. Step 1: Understand the extension method

    The method reversedString() returns a new String made by reversing the characters of the original string.
  2. Step 2: Apply method to 'hello'

    Reversing "hello" results in "olleh".
  3. Final Answer:

    olleh -> Option D
  4. Quick Check:

    String reversed = olleh [OK]
Hint: Remember reversed() returns characters reversed [OK]
Common Mistakes:
  • Expecting original string output
  • Thinking reversed() returns an error
  • Confusing reversed() with reverse()
4. What is wrong with this Swift extension code?
extension Double {
    var squared: Double {
        return self * self
    }

    var storedValue: Double = 0.0
}
medium
A. Extensions cannot add stored properties like 'storedValue'
B. Computed properties must use 'func' keyword
C. The 'squared' property must be a method, not a property
D. The extension must be declared as 'class extension'

Solution

  1. Step 1: Review extension property rules

    Extensions can add computed properties but cannot add stored properties.
  2. Step 2: Identify the stored property

    The line var storedValue: Double = 0.0 tries to add a stored property, which is not allowed.
  3. Final Answer:

    Extensions cannot add stored properties like 'storedValue' -> Option A
  4. Quick Check:

    No stored properties in extensions = A [OK]
Hint: Remember: only computed properties allowed in extensions [OK]
Common Mistakes:
  • Trying to add stored properties in extensions
  • Confusing computed properties with stored properties
  • Thinking extensions require 'class' keyword
5. You want to extend the built-in Array type in Swift to add a method secondElement() that returns the second element if it exists, or nil otherwise. Which of the following extensions correctly implements this?
hard
A. extension Array { func secondElement() -> Element { return self[1] } }
B. extension Array { func secondElement() -> Element? { return self.count > 1 ? self[1] : nil } }
C. extension Array { var secondElement: Element? { if self.count >= 2 { return self[2] } else { return nil } } }
D. extension Array { func secondElement() -> Element? { if self.count > 0 { return self[1] } else { return nil } } }

Solution

  1. Step 1: Check method signature and return type

    The method should return an optional Element (Element?) because the second element might not exist.
  2. Step 2: Verify index and condition

    Arrays are zero-indexed, so the second element is at index 1. The condition should check if count > 1 to safely access index 1.
  3. Step 3: Compare options

    The correct one uses ternary operator: return self.count > 1 ? self[1] : nil. The non-optional return crashes on short arrays. The computed property uses index 2 (third element). The if-else checks count > 0, allowing index 1 access when count == 1, causing runtime crash.
  4. Final Answer:

    extension Array { func secondElement() -> Element? { return self.count > 1 ? self[1] : nil } } -> Option B
  5. Quick Check:

    Safe optional return with index 1 = A [OK]
Hint: Check array count > 1 and return optional Element [OK]
Common Mistakes:
  • Accessing wrong index (like 2 instead of 1)
  • Returning non-optional Element causing crash
  • Using computed property but with wrong index
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard