Recall & Review
beginner
What is an extension with constraints in Swift?
An extension with constraints adds new functionality to a type only when certain conditions are met, like when the type conforms to a specific protocol or has a certain associated type.
Click to reveal answer
beginner
How do you write an extension with a constraint that applies only to arrays of Equatable elements?
You write: <br>
extension Array where Element: Equatable { /* new methods here */ }Click to reveal answer
intermediate
Why use extensions with constraints instead of regular extensions?
Because they let you add features only when the type meets specific requirements, keeping your code safe and relevant to the type's abilities.Click to reveal answer
intermediate
Can you extend a generic type with constraints on its associated types?
Yes, you can add constraints on associated types in extensions to provide functionality only when those associated types meet certain conditions.
Click to reveal answer
intermediate
Example: What does this extension do? <br> <code>extension Collection where Element: Comparable { func isSorted() -> Bool { for i in 1..<count { if self[self.index(startIndex, offsetBy: i)] < self[self.index(startIndex, offsetBy: i - 1)] { return false } } return true } }</code>
It adds a method
isSorted() to any collection whose elements can be compared. This method checks if the collection's elements are in ascending order.Click to reveal answer
What does the 'where' keyword do in a Swift extension with constraints?
✗ Incorrect
The 'where' keyword sets conditions that limit when the extension's code applies, based on the type's properties or protocols.
Which of these is a valid constraint in a Swift extension?
✗ Incorrect
The correct syntax uses 'where' to specify constraints, like 'where Element: Hashable'.
Can you add a method in an extension that only works if the type conforms to a protocol?
✗ Incorrect
Extensions with constraints allow adding methods only when the type meets protocol conformance.
What happens if you try to use a constrained extension on a type that does not meet the constraint?
✗ Incorrect
The extension's methods only exist for types that satisfy the constraints; otherwise, they are unavailable.
Which of these is NOT a valid use of constraints in extensions?
✗ Incorrect
String does not have an 'Element' type alias accessible this way; the syntax is invalid for String.
Explain how extensions with constraints help keep Swift code safe and organized.
Think about when and why you want to add features only to certain types.
You got /4 concepts.
Write a simple Swift extension with a constraint that adds a method only to arrays of integers.
Use 'extension Array where Element == Int' and add a method like sum()
You got /5 concepts.