Challenge - 5 Problems
Swift Extension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of extended String method
What is the output of this Swift code that extends the String type with a method to reverse words?
Swift
extension String { func reversedWords() -> String { self.split(separator: " ").reversed().joined(separator: " ") } } let phrase = "hello world from Swift" print(phrase.reversedWords())
Attempts:
2 left
💡 Hint
Think about what the reversedWords method does to the words in the string.
✗ Incorrect
The extension splits the string into words, reverses the order of the words, then joins them back with spaces. So the output reverses the word order, not the letters.
❓ Predict Output
intermediate2:00remaining
Output of extended Array property
What will this Swift code print when extending Array to add a property that returns the middle element?
Swift
extension Array { var middle: String? { guard !isEmpty else { return nil } return "\(self[count / 2])" } } let numbers = [10, 20, 30, 40, 50] print(numbers.middle ?? "No middle")
Attempts:
2 left
💡 Hint
Remember that integer division truncates the decimal part.
✗ Incorrect
The array has 5 elements, so count is 5. count / 2 is 2, so the element at index 2 is 30.
🔧 Debug
advanced2:00remaining
Why does this extension cause a compile error?
This Swift code tries to add a method to Int to check if it is even. Why does it cause a compile error?
Swift
extension Int { func isEven() -> Bool { self % 2 == 0 } } let number = 4 print(number.isEven)
Attempts:
2 left
💡 Hint
Check how methods are called in Swift.
✗ Incorrect
The method isEven() requires parentheses when called. Using number.isEven without () causes a compile error.
🧠 Conceptual
advanced2:00remaining
Effect of extending built-in types with computed properties
What happens if you add a computed property with the same name as an existing property in a Swift built-in type extension?
Attempts:
2 left
💡 Hint
Think about how Swift handles naming conflicts in extensions.
✗ Incorrect
Swift does not allow extensions to add properties or methods that conflict with existing ones. This causes a compile-time error.
❓ Predict Output
expert2:00remaining
Output of extended Dictionary method with generic constraint
What is the output of this Swift code that extends Dictionary only when its Value type is Int, adding a method to sum all values?
Swift
extension Dictionary where Value == Int { func sumValues() -> Int { self.values.reduce(0, +) } } let scores = ["Alice": 10, "Bob": 20, "Carol": 15] print(scores.sumValues())
Attempts:
2 left
💡 Hint
Check how reduce works on the values collection.
✗ Incorrect
The extension applies only when Value is Int. The sumValues method sums all Int values in the dictionary, so 10 + 20 + 15 = 45.