0
0
Swiftprogramming~20 mins

Extending built-in types in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Extension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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())
A"Swift from world hello"
B"olleh dlrow morf tfiwS"
C"hello world from Swift"
D"Swift from world"
Attempts:
2 left
💡 Hint
Think about what the reversedWords method does to the words in the string.
Predict Output
intermediate
2: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")
ANo middle
B20
C40
D30
Attempts:
2 left
💡 Hint
Remember that integer division truncates the decimal part.
🔧 Debug
advanced
2: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)
ABecause isEven is a method but called without parentheses
BBecause Int cannot be extended
CBecause the modulo operator % is invalid for Int
DBecause the method must be static
Attempts:
2 left
💡 Hint
Check how methods are called in Swift.
🧠 Conceptual
advanced
2: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?
AThe original property is used, ignoring the extension
BThe extension property overrides the original property
CThe compiler throws an error about duplicate definitions
DThe program crashes at runtime
Attempts:
2 left
💡 Hint
Think about how Swift handles naming conflicts in extensions.
Predict Output
expert
2: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())
Anil
B45
C0
DCompilation error
Attempts:
2 left
💡 Hint
Check how reduce works on the values collection.