What if you could add new powers to your code without breaking anything?
Why Extension syntax in Swift? - Purpose & Use Cases
Imagine you have a class for a car, but later you want to add new features like calculating fuel efficiency or printing details. Without extensions, you'd have to rewrite or change the original class code every time.
Changing the original class repeatedly is slow and risky. It can introduce bugs, break existing code, and make your program hard to understand and maintain.
Extension syntax lets you add new features to existing classes, structs, or enums without touching their original code. This keeps your code clean, organized, and safe.
class Car { var model: String init(model: String) { self.model = model } // To add new feature, modify this class directly }
extension Car {
func printDetails() {
print("Car model: \(model)")
}
}You can easily add new abilities to existing types anytime, making your code flexible and easier to grow.
Suppose you have a String type and want to add a function to check if it is a palindrome. Using extension syntax, you add this feature without changing the original String code.
Extension syntax adds new features without changing original code.
Keeps code safe, clean, and easier to maintain.
Helps your program grow flexibly over time.
Practice
extension in Swift?Solution
Step 1: Understand what extensions do
Extensions allow adding new features to existing types without changing their original source code.Step 2: Compare options with this definition
Only adding new functionality to an existing type without modifying its original code correctly describes this purpose. Replacing original implementation refers to overriding, creating subclasses is inheritance, and deleting methods is unrelated to extensions.Final Answer:
To add new functionality to an existing type without modifying its original code -> Option AQuick Check:
Extension purpose = Add features without changing original code [OK]
- Confusing extensions with subclassing
- Thinking extensions replace original code
- Believing extensions can remove methods
String type in Swift?Solution
Step 1: Recall Swift extension syntax
The correct syntax starts with the keywordextensionfollowed by the type name without parentheses or brackets.Step 2: Check each option
extension String { }uses correct syntax.extend String { }uses invalid keyword.extension String() { }adds invalid parentheses.extension String[] { }uses invalid array notation.Final Answer:
extension String { } -> Option BQuick Check:
Extension syntax = extension TypeName { } [OK]
- Using 'extend' instead of 'extension'
- Adding parentheses after type name
- Using brackets after type name
extension Int {
func squared() -> Int {
return self * self
}
}
let number = 4
print(number.squared())Solution
Step 1: Understand the extension method
The extension adds a methodsquared()to Int that returns the number multiplied by itself.Step 2: Calculate the output for number = 4
Calling4.squared()returns 4 * 4 = 16.Final Answer:
16 -> Option AQuick Check:
4 squared = 16 [OK]
- Confusing squared with doubling
- Expecting syntax error due to extension
- Forgetting to return the value
extension Double {
func half() -> Double {
self / 2
}
}Solution
Step 1: Check method syntax in extension
In Swift, single-expression functions can omit thereturnkeyword.Step 2: Verify if extension on Double is allowed
Extensions can add methods to Double. The method name 'half' is valid.Final Answer:
No error, code is correct -> Option DQuick Check:
Single-expression methods can omit return [OK]
- Assuming 'return' is always required
- Thinking extensions can't add methods to built-in types
- Believing method names have restrictions
isEven to Int using an extension that returns true if the number is even, otherwise false. Which code correctly implements this?Solution
Step 1: Understand computed property syntax
Computed properties usevarwith 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.Step 2: Check logic correctness
extension Int { var isEven: Bool { self % 2 == 0 } }uses concise expressionself % 2 == 0which 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.Step 3: Verify distractors
The method requires parentheses to call likenum.isEven(). Incomplete if fails to compile. Division fails for even numbers like 2 (2/2 == 1 != 0).Final Answer:
extension Int { var isEven: Bool { self % 2 == 0 } } -> Option CQuick Check:
Computed property with modulo check = extension Int { var isEven: Bool { self % 2 == 0 } } [OK]
- Using division instead of modulo
- Confusing method with computed property
- Forgetting to return a Bool value
Ready to prove it?
Pass the test and this pattern moves unknown
