What is the output of this Swift code?
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())
Check how the extension applies only when Element conforms to Describable.
The extension adds allDescriptions() only to arrays whose elements conform to Describable. Since Item conforms, calling allDescriptions() returns an array of descriptions.
What will this Swift code print?
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())
Remember the extension applies to arrays of Vehicle or subclasses.
The extension adds totalWheels() to arrays of Vehicle or subclasses. It sums wheels of all elements: 4 + 2 = 6.
Why does this Swift extension cause a compilation error?
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 } }
Check if the operator used is guaranteed by the protocols.
The error is because Element conforms to Equatable and Comparable, but Comparable requires < and ==, not necessarily <=. The operator <= is not guaranteed.
Which option shows the correct syntax to extend Array only when its elements conform to Hashable?
Remember the syntax for constrained extensions uses 'where'.
The correct syntax is extension Array where Element: Hashable {}. Option A and C are invalid syntax. Option A uses '==' which means equality, not conformance.
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?
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 } }
Check the correct syntax for multiple protocol constraints in extensions.
Option A correctly uses where Element: Numeric & Comparable to constrain the extension. Option A uses a comma which is invalid syntax. Option A incorrectly uses generic parameter syntax. Option A uses '==' which means equality, not conformance.