0
0
Swiftprogramming~5 mins

Extending built-in types in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean to extend a built-in type in Swift?
Extending a built-in type means adding new features like methods, computed properties, or initializers to existing types such as Int, String, or Array without changing their original code.
Click to reveal answer
beginner
How do you declare an extension for a built-in type in Swift?
Use the keyword extension followed by the type name, then add new methods or properties inside curly braces. For example: <br>
extension Int {<br>  func squared() -> Int {<br>    return self * self<br>  }<br>}
Click to reveal answer
intermediate
Can extensions add stored properties to built-in types in Swift?
No, extensions cannot add stored properties. They can only add computed properties, methods, initializers, and nested types.
Click to reveal answer
beginner
Why might you want to extend a built-in type?
To add useful functionality that fits your app's needs without subclassing or rewriting the original type. For example, adding a method to format a number or check a string's content.
Click to reveal answer
intermediate
Example: What does this Swift extension do?<br><pre>extension String {<br>  var isPalindrome: Bool {<br>    let cleaned = self.lowercased().filter { $0.isLetter }<br>    return cleaned == String(cleaned.reversed())<br>  }<br>}</pre>
It adds a computed property isPalindrome to String that returns true if the string reads the same forwards and backwards, ignoring case and non-letter characters.
Click to reveal answer
Which keyword is used to add new functionality to a built-in type in Swift?
Aoverride
Binheritance
Cextension
Dprotocol
Can you add stored properties to a built-in type using an extension?
AYes, always
BNo, never
COnly if the type is a class
DOnly if the property is static
What is the value of 5.squared() if extension Int { func squared() -> Int { self * self } } is defined?
A25
B10
C5
DError
Which of these can you add to a built-in type using an extension?
AChange stored property values
BStored properties
CChange existing method implementations
DComputed properties
Why are extensions useful in Swift?
AThey let you add functionality without subclassing
BThey replace the original type's code
CThey allow modifying private properties
DThey make types mutable
Explain how to extend a built-in type in Swift and what you can add with an extension.
Think about adding new abilities to a type without changing its original code.
You got /5 concepts.
    Describe a real-life example where extending a built-in type would be helpful.
    Imagine you want to add a shortcut to check or transform data on a common type.
    You got /4 concepts.