0
0
Swiftprogramming~20 mins

CompactMap for optional unwrapping in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift CompactMap Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What 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)
A[1, 3, 0, 7]
B[1, 3, 7]
C[1, 3, nil, 7]
DCompilation error
Attempts:
2 left
💡 Hint
Remember that compactMap removes nil values after transformation.
Predict Output
intermediate
2:00remaining
What 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)
A[10, 20, 30]
B["10", "20", "30"]
C[10, 20, nil, 30]
DRuntime error
Attempts:
2 left
💡 Hint
Two compactMaps are used: first to remove nils, second to convert strings to Ints.
🔧 Debug
advanced
2:00remaining
Why 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)
AThe array contains invalid strings causing crash.
BcompactMap cannot be used with optionals.
CInt initializer throws an error for nil strings.
DForce unwrapping nil causes a runtime crash.
Attempts:
2 left
💡 Hint
Look at the use of force unwrap (!) inside the closure.
📝 Syntax
advanced
2:00remaining
Which 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.
A
let arr: [String?] = ["2", nil, "4", "six", "6"]
let nums = arr.compactMap { $0 != nil ? Int($0!) : nil }
print(nums)
B
let arr: [String?] = ["2", nil, "4", "six", "6"]
let nums = arr.compactMap { Int($0) }
print(nums)
C
let arr: [String?] = ["2", nil, "4", "six", "6"]
let nums = arr.compactMap { Int($0 ?? "") }
print(nums)
D
let arr: [String?] = ["2", nil, "4", "six", "6"]
let nums = arr.compactMap { Int($0!) }
print(nums)
Attempts:
2 left
💡 Hint
Avoid force unwrapping nil values to prevent crashes.
🚀 Application
expert
2:00remaining
How 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) }
A3
B4
C5
D6
Attempts:
2 left
💡 Hint
Count how many strings convert successfully to Int after removing nils.