Bird
Raised Fist0
Swiftprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the compactMap function do when used on an array of optionals in Swift?
easy
A. It unwraps optionals and removes all nil values from the array.
B. It converts all values to strings regardless of their type.
C. It sorts the array in ascending order.
D. It replaces all nil values with zero.

Solution

  1. Step 1: Understand what compactMap does

    compactMap takes an array of optionals and unwraps each element, removing any nil values.
  2. Step 2: Compare with other options

    It does not convert types, sort, or replace nil with zero. It only filters out nil and unwraps values.
  3. Final Answer:

    It unwraps optionals and removes all nil values from the array. -> Option A
  4. Quick Check:

    compactMap removes nil = B [OK]
Hint: Remember: compactMap unwraps and drops nils [OK]
Common Mistakes:
  • Confusing compactMap with map (which keeps nils)
  • Thinking compactMap sorts or changes types
  • Assuming compactMap replaces nil with default values
2. Which of the following is the correct syntax to use compactMap on an array numbers of type [Int?] to get an array of non-optional Int values?
easy
A. let result = numbers.compactMap { $0 }
B. let result = numbers.compactMap { Int($0) }
C. let result = numbers.compactMap { $0! }
D. let result = numbers.compactMap { String($0) }

Solution

  1. Step 1: Understand the input and output types

    numbers is an array of optional integers [Int?]. We want to unwrap and remove nil values to get [Int].
  2. Step 2: Check each option's correctness

    let result = numbers.compactMap { $0 } uses compactMap { $0 } which unwraps optionals and removes nil. let result = numbers.compactMap { Int($0) } tries to convert optional Int to Int again, which is unnecessary. let result = numbers.compactMap { $0! } force unwraps, which can crash if nil. let result = numbers.compactMap { String($0) } converts to String, changing type.
  3. Final Answer:

    let result = numbers.compactMap { $0 } -> Option A
  4. Quick Check:

    Use compactMap with identity closure to unwrap optionals [OK]
Hint: Use compactMap { $0 } to unwrap optionals safely [OK]
Common Mistakes:
  • Using force unwrap inside compactMap causing runtime errors
  • Trying to convert optionals unnecessarily
  • Changing the type unintentionally
3. What is the output of the following Swift code?
let values: [Int?] = [1, nil, 3, nil, 5]
let unwrapped = values.compactMap { $0 }
print(unwrapped)
medium
A. Compilation error
B. [1, 3, 5]
C. [1, nil, 3, nil, 5]
D. [Optional(1), Optional(3), Optional(5)]

Solution

  1. Step 1: Understand the input array

    The array values contains optional integers with some nil values.
  2. Step 2: Apply compactMap

    compactMap { $0 } unwraps optionals and removes nil values, resulting in [1, 3, 5].
  3. Final Answer:

    [1, 3, 5] -> Option B
  4. Quick Check:

    compactMap removes nils and unwraps = [1, 3, 5] [OK]
Hint: compactMap removes nils and unwraps optionals [OK]
Common Mistakes:
  • Expecting optionals in output instead of unwrapped values
  • Thinking nils remain in the output
  • Confusing compactMap with map
4. Identify the error in this Swift code snippet and choose the correct fix:
let strings: [String?] = ["apple", nil, "banana"]
let lengths = strings.compactMap { $0.count }
print(lengths)
medium
A. Error: Use force unwrap $0! before accessing count
B. Error: compactMap should be replaced with map
C. No error; code runs correctly
D. Error: Cannot use $0.count on optional; fix by using compactMap { $0?.count }

Solution

  1. Step 1: Analyze the closure inside compactMap

    The closure uses $0.count, but $0 is an optional String?. Accessing count directly on optional causes error.
  2. Step 2: Correct the closure to safely unwrap

    Using $0?.count returns an optional Int, which compactMap unwraps and removes nils, fixing the error.
  3. Final Answer:

    Error: Cannot use $0.count on optional; fix by using compactMap { $0?.count } -> Option D
  4. Quick Check:

    Use optional chaining inside compactMap closure [OK]
Hint: Use optional chaining ($0?.property) inside compactMap [OK]
Common Mistakes:
  • Trying to access property directly on optional causing error
  • Using map instead of compactMap losing nil filtering
  • Force unwrapping causing runtime crashes
5. Given a dictionary [String: Int?] representing item stock counts, how can you create a new dictionary with only items that have a non-nil stock count using compactMap or similar methods?
hard
A. Use filter { $0.value != nil } without unwrapping values.
B. Use mapValues { $0! } to force unwrap all values.
C. Use compactMapValues { $0 } to unwrap and filter out nil values.
D. Use compactMap { $0 } directly on the dictionary.

Solution

  1. Step 1: Understand dictionary optional values

    The dictionary has optional Int values. We want to remove keys with nil values and unwrap the rest.
  2. Step 2: Use compactMapValues to unwrap and filter

    compactMapValues { $0 } unwraps optionals in values and removes entries with nil values, producing a dictionary with non-optional Int values.
  3. Final Answer:

    Use compactMapValues { $0 } to unwrap and filter out nil values. -> Option C
  4. Quick Check:

    compactMapValues unwraps and filters dictionary values [OK]
Hint: Use compactMapValues to unwrap and remove nil dictionary values [OK]
Common Mistakes:
  • Using mapValues with force unwrap risking crashes
  • Filtering without unwrapping values
  • Trying to use compactMap directly on dictionary
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard