Introduction
Extending built-in types lets you add new features to existing types, like numbers or strings, without changing their original code.
extension TypeName { // new methods or computed properties }
extension Int { func squared() -> Int { return self * self } }
extension String { var reversedString: String { return String(self.reversed()) } }
extension Int { func squared() -> Int { return self * self } } let number = 5 print("The square of \(number) is \(number.squared())")
Int type with a method isEven() that returns a Bool?extension to add methods to existing types.func isEven() -> Bool. The body uses self % 2 == 0.extension String {
func reversedString() -> String {
return String(self.reversed())
}
}
let word = "hello"
print(word.reversedString())reversedString() returns a new String made by reversing the characters of the original string.extension Double {
var squared: Double {
return self * self
}
var storedValue: Double = 0.0
}var storedValue: Double = 0.0 tries to add a stored property, which is not allowed.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?Element?) because the second element might not exist.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.Pass the test and this pattern moves unknown