Complete the code to unwrap optionals using compactMap.
let numbers: [Int?] = [1, nil, 3, nil, 5] let unwrapped = numbers.[1] { $0 }
The compactMap method unwraps optionals and removes nil values from the array.
Complete the code to unwrap and double the numbers using compactMap.
let numbers: [Int?] = [2, nil, 4, nil, 6] let doubled = numbers.compactMap { [1] }
The closure unwraps each optional and doubles the value. compactMap removes nils.
Fix the error in the code to unwrap optionals correctly with compactMap.
let strings: [String?] = ["1", nil, "3", "four"] let numbers = strings.compactMap { Int([1]) }
String($0) is redundant.Int(Int($0)), causing a compiler error.The closure receives a String?. Pass $0 to Int(_:), which safely returns Int? for compactMap to unwrap non-nil values.
Fill both blanks to create a dictionary of word lengths, ignoring short words.
let words = ["apple", "to", "banana", "go"] let lengths = Dictionary(uniqueKeysWithValues: words.filter { $0.count > 2 }.map { ([1], [2]) })
The dictionary uses the word as key and its count as value, filtering words longer than 2.
Fill all three blanks to filter and transform optional strings to uppercase.
let optionalStrings: [String?] = ["cat", nil, "dog", ""] let result = optionalStrings.compactMap { [1] in guard let str = [2], !str.isEmpty else { return nil } return [3] }
The closure parameter is named str (optional string). Guard unwraps str (shadowing the parameter), checks non-empty, returns uppercase.