What if you could teach numbers and strings new tricks, just like your own custom tools?
Why Extending built-in types in Swift? - Purpose & Use Cases
Imagine you want to add a new feature to a number or a string in your program, like making a number tell if it's even or odd, but the built-in number type doesn't have that feature.
You try to write separate functions everywhere to check this, but it feels messy and repetitive.
Writing separate functions for every new feature is slow and confusing.
You have to remember to call the right function each time, and it's easy to make mistakes or forget.
Your code becomes long and hard to read because the new features don't feel like they belong to the numbers or strings themselves.
Extending built-in types lets you add new features directly to existing types like numbers or strings.
This means you can call your new features just like the built-in ones, making your code cleaner and easier to understand.
func isEven(_ number: Int) -> Bool {
return number % 2 == 0
}
let result = isEven(4)extension Int {
var isEven: Bool {
return self % 2 == 0
}
}
let result = 4.isEvenYou can make your code more natural and expressive by adding your own features to existing types.
Imagine adding a feature to the String type that tells if a password is strong, so you can just write password.isStrong instead of calling a separate function.
Manual functions for new features are repetitive and messy.
Extending built-in types adds features directly to existing types.
This makes code cleaner, easier to read, and more natural.
Practice
Solution
Step 1: Understand what extensions do
Extensions allow adding new methods or computed properties to existing types without subclassing.Step 2: Identify what extensions cannot do
Extensions cannot add stored properties or delete existing methods.Final Answer:
To add new methods or computed properties to existing types -> Option CQuick Check:
Extensions add methods/properties = B [OK]
- Thinking extensions can add stored properties
- Confusing extensions with subclassing
- Believing extensions can remove methods
Int type with a method isEven() that returns a Bool?Solution
Step 1: Identify the correct keyword for extension
Swift uses the keywordextensionto add methods to existing types.Step 2: Check method syntax
The method must have parentheses and a return type:func isEven() -> Bool. The body usesself % 2 == 0.Final Answer:
extension Int { func isEven() -> Bool { return self % 2 == 0 } } -> Option AQuick Check:
Correct extension syntax = D [OK]
- Using 'extend' instead of 'extension'
- Omitting parentheses in method declaration
- Missing 'func' keyword before method name
extension String {
func reversedString() -> String {
return String(self.reversed())
}
}
let word = "hello"
print(word.reversedString())What is the output when this code runs?
Solution
Step 1: Understand the extension method
The methodreversedString()returns a new String made by reversing the characters of the original string.Step 2: Apply method to 'hello'
Reversing "hello" results in "olleh".Final Answer:
olleh -> Option DQuick Check:
String reversed = olleh [OK]
- Expecting original string output
- Thinking reversed() returns an error
- Confusing reversed() with reverse()
extension Double {
var squared: Double {
return self * self
}
var storedValue: Double = 0.0
}Solution
Step 1: Review extension property rules
Extensions can add computed properties but cannot add stored properties.Step 2: Identify the stored property
The linevar storedValue: Double = 0.0tries to add a stored property, which is not allowed.Final Answer:
Extensions cannot add stored properties like 'storedValue' -> Option AQuick Check:
No stored properties in extensions = A [OK]
- Trying to add stored properties in extensions
- Confusing computed properties with stored properties
- Thinking extensions require 'class' keyword
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?Solution
Step 1: Check method signature and return type
The method should return an optional Element (Element?) because the second element might not exist.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.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.Final Answer:
extension Array { func secondElement() -> Element? { return self.count > 1 ? self[1] : nil } } -> Option BQuick Check:
Safe optional return with index 1 = A [OK]
- Accessing wrong index (like 2 instead of 1)
- Returning non-optional Element causing crash
- Using computed property but with wrong index
Ready to prove it?
Pass the test and this pattern moves unknown
