0
0
Swiftprogramming~10 mins

Extensions with constraints in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to extend Array only when its elements conform to Equatable.

Swift
extension Array where Element: [1] {
    func containsElement(_ element: Element) -> Bool {
        return self.contains(element)
    }
}
Drag options to blanks, or click blank then click option'
AHashable
BComparable
CEquatable
DCodable
Attempts:
3 left
💡 Hint
Common Mistakes
Using a protocol that doesn't support equality checking like Comparable.
Forgetting to add the constraint after 'where Element:'.
2fill in blank
medium

Complete the code to add a method only for Dictionary where Key is String.

Swift
extension Dictionary where [1] == String {
    func allKeys() -> [String] {
        return Array(self.keys)
    }
}
Drag options to blanks, or click blank then click option'
AKey
BElement
CSelf
DValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Value' instead of 'Key' in the constraint.
Using 'Element' which is not a dictionary type alias.
3fill in blank
hard

Fix the error in the extension to add a method only when Element conforms to Numeric.

Swift
extension Array where Element: [1] {
    func sum() -> Element {
        return self.reduce(0, +)
    }
}
Drag options to blanks, or click blank then click option'
ACodable
BComparable
CEquatable
DNumeric
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Comparable' which does not guarantee addition.
Using 'Equatable' which only supports equality checks.
4fill in blank
hard

Fill both blanks to extend Sequence only when Element is Hashable and add a method to get unique elements.

Swift
extension Sequence where [1]: [2] {
    func uniqueElements() -> [Element] {
        var seen = Set<Element>()
        return self.filter { seen.insert($0).inserted }
    }
}
Drag options to blanks, or click blank then click option'
AElement
BHashable
CEquatable
DComparable
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Equatable' instead of 'Hashable' which is needed for Set.
Using 'Sequence' instead of 'Element' in the constraint.
5fill in blank
hard

Fill all three blanks to extend Optional only when Wrapped is Comparable and add a method to compare with another Optional.

Swift
extension Optional where [1]: [2] {
    func isGreater(than other: Optional<[3]>) -> Bool {
        switch (self, other) {
        case let (.some(a), .some(b)):
            return a > b
        default:
            return false
        }
    }
}
Drag options to blanks, or click blank then click option'
AWrapped
BComparable
DEquatable
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Equatable' instead of 'Comparable' which does not support > operator.
Using 'Optional' instead of 'Wrapped' in the constraint.