0
0
Swiftprogramming~10 mins

CompactMap for optional unwrapping in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to unwrap optionals using compactMap.

Swift
let numbers: [Int?] = [1, nil, 3, nil, 5]
let unwrapped = numbers.[1] { $0 }
Drag options to blanks, or click blank then click option'
AcompactMap
Bmap
Cfilter
DflatMap
Attempts:
3 left
💡 Hint
Common Mistakes
Using map keeps nil values, resulting in an array of optionals.
Using filter only filters but does not unwrap optionals.
2fill in blank
medium

Complete the code to unwrap and double the numbers using compactMap.

Swift
let numbers: [Int?] = [2, nil, 4, nil, 6]
let doubled = numbers.compactMap { [1] }
Drag options to blanks, or click blank then click option'
A$0 ?? 0
B$0 + 2
C$0
D$0 * 2
Attempts:
3 left
💡 Hint
Common Mistakes
Using $0 ?? 0 returns 0 for nils, which compactMap does not require.
Using map instead of compactMap keeps nils.
3fill in blank
hard

Fix the error in the code to unwrap optionals correctly with compactMap.

Swift
let strings: [String?] = ["1", nil, "3", "four"]
let numbers = strings.compactMap { Int([1]) }
Drag options to blanks, or click blank then click option'
AString($0)
B$0
C$0 ?? "0"
DInt($0)
Attempts:
3 left
💡 Hint
Common Mistakes
Using $0 ?? "0" converts nils to "0", which changes the logic.
Using String($0) is redundant.
Option D creates Int(Int($0)), causing a compiler error.
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths, ignoring short words.

Swift
let words = ["apple", "to", "banana", "go"]
let lengths = Dictionary(uniqueKeysWithValues: words.filter { $0.count > 2 }.map { ([1], [2]) })
Drag options to blanks, or click blank then click option'
Aword
Bword.count
Clen(word)
Dword.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using len(word) or word.length which are not valid in Swift.
Using word.count in the key position instead of the value.
5fill in blank
hard

Fill all three blanks to filter and transform optional strings to uppercase.

Swift
let optionalStrings: [String?] = ["cat", nil, "dog", ""]
let result = optionalStrings.compactMap { [1] in
    guard let str = [2], !str.isEmpty else { return nil }
    return [3]
}
Drag options to blanks, or click blank then click option'
Astr
B$0
Cstr.uppercased()
DoptionalStrings
Attempts:
3 left
💡 Hint
Common Mistakes
Using $0 as closure parameter causes syntax error here.
Returning the original string instead of uppercase.
Not unwrapping the optional properly.