4. Identify the error in this Swift extension code:
extension Int {
func squared() -> Int {
return self * self
}
}
let result = 5.squared
print(result)
medium
A. Cannot extend Int type
B. squared() must be static method
C. self keyword not allowed in extensions
D. Missing parentheses when calling squared()
Solution
Step 1: Check method call syntax
The method squared() is defined correctly, but calling 5.squared misses parentheses.
Step 2: Understand method call requirements
In Swift, methods must be called with parentheses even if no parameters, so 5.squared() is correct.
Final Answer:
Missing parentheses when calling squared() -> Option D
Quick Check:
Method call needs () = B [OK]
Hint: Call methods with () even if no parameters [OK]
Common Mistakes:
Calling methods without parentheses
Thinking Int cannot be extended
Believing self is disallowed in extensions
5. You want to add a computed property isEven to Int using an extension that returns true if the number is even. Which code correctly achieves this without modifying the original Int type?
hard
A. extension Int { static var isEven: Bool { self % 2 == 0 } }
B. extension Int { func isEven() -> Bool { self % 2 == 0 } }
C. extension Int { var isEven: Bool { self % 2 == 0 } }
D. extension Int { var isEven: Bool { return self / 2 == 0 } }
Solution
Step 1: Understand computed property syntax
Computed properties use 'var name: Type { expression }' without parentheses.
Step 2: Check each option
extension Int { var isEven: Bool { self % 2 == 0 } } correctly defines a computed property isEven returning true if self % 2 == 0. extension Int { func isEven() -> Bool { self % 2 == 0 } } uses a method, not a property. extension Int { static var isEven: Bool { self % 2 == 0 } } incorrectly uses static. extension Int { var isEven: Bool { return self / 2 == 0 } } uses wrong logic (division instead of modulo).
Final Answer:
extension Int { var isEven: Bool { self % 2 == 0 } } -> Option C
Quick Check:
Computed property with modulo check = A [OK]
Hint: Computed properties use var without parentheses [OK]
Common Mistakes:
Using func instead of var for computed property
Making property static when it should be instance
Using division instead of modulo for even check
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.