Challenge - 5 Problems
Swift CompactMap Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Swift code using compactMap?
Consider the following Swift code snippet that uses
compactMap to unwrap optionals. What will be printed?Swift
let numbers: [String?] = ["1", nil, "3", "five", "7"] let validInts = numbers.compactMap { Int($0 ?? "") } print(validInts)
Attempts:
2 left
💡 Hint
Remember that compactMap removes nil values after transformation.
✗ Incorrect
The compactMap tries to convert each optional string to an Int. If conversion fails or the value is nil, it is skipped. "five" cannot be converted, so it is removed. nil is also removed. The result is [1, 3, 7].
❓ Predict Output
intermediateWhat does this compactMap expression produce?
Given this Swift code, what is the value of
result?Swift
let array: [String?] = ["10", "20", nil, "abc", "30"] let result = array.compactMap { $0 }.compactMap { Int($0) } print(result)
Attempts:
2 left
💡 Hint
Two compactMaps are used: first to remove nils, second to convert strings to Ints.
✗ Incorrect
The first compactMap removes nil values, resulting in ["10", "20", "abc", "30"]. The second compactMap converts strings to Ints, skipping "abc" which fails conversion. Final result is [10, 20, 30].
🔧 Debug
advancedWhy does this compactMap code cause a runtime error?
Examine this Swift code snippet. It compiles but crashes at runtime. What causes the crash?
Swift
let strings: [String?] = ["5", nil, "15"] let numbers = strings.compactMap { Int($0!) } print(numbers)
Attempts:
2 left
💡 Hint
Look at the use of force unwrap (!) inside the closure.
✗ Incorrect
The code force unwraps $0 with $0!, but some elements are nil. Force unwrapping nil causes a runtime crash (fatal error).
📝 Syntax
advancedWhich option correctly uses compactMap to unwrap optionals and convert to Int?
Choose the Swift code snippet that compiles and produces [2, 4, 6] from the array ["2", nil, "4", "six", "6"] using compactMap.
Attempts:
2 left
💡 Hint
Avoid force unwrapping nil values to prevent crashes.
✗ Incorrect
Option C safely unwraps optionals with $0 ?? "" and tries to convert to Int. Invalid strings convert to nil and are removed. Option C force unwraps nil causing a crash. Option C tries to convert optional String? directly to Int which is invalid.
🚀 Application
expertHow many elements are in the resulting array after this compactMap chain?
Given this Swift code, how many elements does
finalArray contain?Swift
let data: [String?] = ["100", "abc", nil, "200", "300", "xyz", nil] let finalArray = data.compactMap { $0 }.compactMap { Int($0) }
Attempts:
2 left
💡 Hint
Count how many strings convert successfully to Int after removing nils.
✗ Incorrect
First compactMap removes nils: ["100", "abc", "200", "300", "xyz"]. Second compactMap converts to Int, skipping "abc" and "xyz". Valid ints are 100, 200, 300, so 3 elements.
