0
0
Swiftprogramming~10 mins

Map, filter, reduce patterns 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 create a new array with each number doubled using map.

Swift
let numbers = [1, 2, 3, 4]
let doubled = numbers.[1] { $0 * 2 }
Drag options to blanks, or click blank then click option'
Afilter
Breduce
Cmap
DcompactMap
Attempts:
3 left
💡 Hint
Common Mistakes
Using filter instead of map, which only selects elements but does not transform them.
2fill in blank
medium

Complete the code to filter out numbers less than 3.

Swift
let numbers = [1, 2, 3, 4, 5]
let filtered = numbers.[1] { $0 >= 3 }
Drag options to blanks, or click blank then click option'
Afilter
Breduce
Cmap
DflatMap
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of filter, which transforms elements but does not remove any.
3fill in blank
hard

Fix the error in the code to sum all numbers using reduce.

Swift
let numbers = [1, 2, 3, 4]
let sum = numbers.reduce([1]) { $0 + $1 }
Drag options to blanks, or click blank then click option'
A1
B0
C[]
D""
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as initial value, which adds an extra 1 to the sum.
Using an empty array or string, which causes a type error.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths as values, filtering words longer than 3 characters.

Swift
let words = ["apple", "bat", "car", "door"]
let lengths = Dictionary(uniqueKeysWithValues: words.filter { $0.count [1] 3 }.map { [2] in ([2], [2].count) })
Drag options to blanks, or click blank then click option'
A>
B<
Cword
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the filter condition.
Using 'count' instead of 'word' as the key in the tuple.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys, their counts as values, filtering words with count greater than 1.

Swift
let words = ["apple", "bat", "apple", "car", "bat", "bat"]
let counts = words.reduce(into: [:]) { counts, [1] in
    counts[[2]] = (counts[[3]] ?? 0) + 1
}
let filteredCounts = counts.filter { $0.value > 1 }
Drag options to blanks, or click blank then click option'
Aword
Bword.uppercased()
Attempts:
3 left
💡 Hint
Common Mistakes
Using the lowercase word as key instead of uppercase.
Using inconsistent keys for reading and writing counts.