0
0
Swiftprogramming~20 mins

Extensions with constraints in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Extensions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of extension with protocol constraint

What is the output of this Swift code?

Swift
protocol Describable {
    func describe() -> String
}

struct Item: Describable {
    var name: String
    func describe() -> String {
        return "Item: \(name)"
    }
}

extension Array where Element: Describable {
    func allDescriptions() -> [String] {
        self.map { $0.describe() }
    }
}

let items = [Item(name: "Pen"), Item(name: "Book")]
print(items.allDescriptions())
ACompilation error: 'describe()' not found
B["Pen", "Book"]
C["Item: Pen", "Item: Book"]
DRuntime error: Cannot convert value
Attempts:
2 left
💡 Hint

Check how the extension applies only when Element conforms to Describable.

Predict Output
intermediate
2:00remaining
Extension with class constraint output

What will this Swift code print?

Swift
class Vehicle {
    var wheels: Int
    init(wheels: Int) {
        self.wheels = wheels
    }
}

class Car: Vehicle {}

extension Array where Element: Vehicle {
    func totalWheels() -> Int {
        self.reduce(0) { $0 + $1.wheels }
    }
}

let vehicles: [Vehicle] = [Car(wheels: 4), Vehicle(wheels: 2)]
print(vehicles.totalWheels())
ACompilation error: Cannot extend Array with class constraint
B6
CRuntime error: Method not found
D4
Attempts:
2 left
💡 Hint

Remember the extension applies to arrays of Vehicle or subclasses.

🔧 Debug
advanced
2:00remaining
Why does this extension not compile?

Why does this Swift extension cause a compilation error?

Swift
extension Array where Element: Equatable & Comparable {
    func isSortedAndUnique() -> Bool {
        for i in 1..<self.count {
            if self[i] <= self[i-1] {
                return false
            }
        }
        return true
    }
}
ASwift does not allow multiple protocol constraints with '&' in extensions
BThe syntax for multiple constraints should use a where clause with commas, not '&'
CThe extension requires Element to be a class, but protocols are used
DThe operator '<=' is not defined for Element
Attempts:
2 left
💡 Hint

Check if the operator used is guaranteed by the protocols.

📝 Syntax
advanced
2:00remaining
Correct syntax for extension with generic constraint

Which option shows the correct syntax to extend Array only when its elements conform to Hashable?

Aextension Array where Element: Hashable {}
Bextension Array where Element == Hashable {}
Cextension Array<Element> where Element: Hashable {}
Dextension Array<Element: Hashable> {}
Attempts:
2 left
💡 Hint

Remember the syntax for constrained extensions uses 'where'.

🚀 Application
expert
3:00remaining
Implement extension with multiple constraints

Given the following code, which option correctly implements an extension on Array where Element is both Numeric and Comparable, adding a method maxValue() that returns the maximum element?

Swift
extension Array where Element: Numeric & Comparable {
    func maxValue() -> Element? {
        guard var maxElem = self.first else { return nil }
        for elem in self {
            if elem > maxElem {
                maxElem = elem
            }
        }
        return maxElem
    }
}
A
extension Array where Element: Numeric &amp; Comparable {
    func maxValue() -&gt; Element? {
        self.max()
    }
}
B
extension Array where Element: Numeric, Comparable {
    func maxValue() -&gt; Element? {
        self.max()
    }
}
C
extension Array&lt;Element&gt; where Element: Numeric &amp; Comparable {
    func maxValue() -&gt; Element? {
        self.max()
    }
}
D
extension Array where Element == Numeric &amp; Comparable {
    func maxValue() -&gt; Element? {
        self.max()
    }
}
Attempts:
2 left
💡 Hint

Check the correct syntax for multiple protocol constraints in extensions.