map
, filter
, and reduce
Swift provides powerful functions for working with arrays: map
, filter
, and reduce
. These functions allow you to transform, filter, and combine array elements.
Before we go on, hereโs some tips for users of other programming languages this year:
map
and filter
. However, reduce
is called fold
.map
, filter
, and reduce
for Streams only.Select
, Where
, and Aggregate
. You need to use LINQ in your project.std::transform
, std::copy_if
, and either std::reduce
or std::accumulate
depending on your needs.In this example, the function accepts one parameter called number
and returns the square of that number. This function is applied to each of the numbers in the numbers
array, creating a new array containing the squared numbers.
filter
The filter
function removes elements that donโt match a condition.
The basic structure of function
looks like this:
let result = myArray.filter { item in
return item == conditionalValue
}
map
:{ item in ... }
: This is a function that takes one parameter:
item
: The next value in the array.true
or false
. If it returns true
, the item is included in the new array.for
loop in Python:numbers = [1, 2, 3, 4, 5]
even_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
print(even_numbers) # Output: [2, 4]
filter
in Swift:let numbers = [1, 2, 3, 4, 5]
let evenNumbers = numbers.filter { number in
return number % 2 == 0
}
print(evenNumbers) // Output: [2, 4]
In this example, removes any number that does not satisfy the condition (i.e., not even). That is because number % 2 == 0
is a Boolean expression that returns true
or false
.
filter
Use filter
to use only words that are longer than four (4) characters. Print out the new array of words.
let words = ["apple", "cat", "banana", "dog", "grape", "kiwi"]
reduce
The reduce
function is a way to combine all elements in a array into a single value. If youโve used for
loops in Python to sum numbers or join strings, reduce
does the same thing, but in a more compact way.
The basic structure of reduce
looks like this:
let result = array.reduce(initialValue) { result, item in
return result + item
}
reduce
:initialValue
: This is where the total starts (like 0
for sum or ""
for a sentence).{ result, item in ... }
: This is a function that takes two parameters:
result
: The value so far.item
: The next value in the array.for
loop in Python:numbers = [1, 2, 3, 4, 5]
total = 0
for number in numbers:
total += number
print(total) # Output: 15
reduce
in Swift:let numbers = [1, 2, 3, 4, 5]
let total = numbers.reduce(0) { result, number in
return result + number
}
print(total) // Output: 15
Each number is added to the total, just like in the loop. However, using reduce
avoids having to create a variable (which would, otherwise, never be modified). Remember that avoiding unnecessary var
is a desirable behaviour in Swift as it makes code more secure by preventing accidental overwriting of data that should be protected!
for
loop in Pythonvalues = [3, 7, 2, 8, 5]
max_value = values
for value in values:
if value > max_value:
max_value = value
print(max_value) # Output: 8
let values = [3, 7, 2, 8, 5]
let maxValue = values.reduce(values) { result, number in
return max(result, number)
}
print(maxValue) // Output: 8
This checks each number and keeps the biggest one.
In the example, the initial value is set to the first value in the values
array; the max
function then compares that number (result
, currently 3
) with the next number (number
, which is 7
in the first run). The largest value (7
) is returned, replacing the initial value (and result
) with 7
. In the next run, 7
is compared with 2
; as 7
is still the largest value, it is returned again.
for
loop in Pythonwords = ["Python", "is", "fun"]
sentence = ""
for word in words:
sentence = sentence + " " + word.upper()
print(sentence)
reduce
in Swiftlet words = ["Swift", "is", "fun"]
let sentence = words.reduce("") { result, word in
return result + " " + word.uppercased()
}
print(sentence) // Output: " SWIFT IS FUN"
This builds a sentence by adding spaces between words.
reduce
Use reduce
to find the product of all numbers in an array. Print the new array.
let numbers = [7, 14, 21, 28, 35]
Use reduce
to find the longest word in an array. The initial value can be an empty string (""
).
You can find the length of a word using the .count
property. For example, "hello".count
or someWord.count
. This is equivalent to Pythonโs len("hello")
and len(some_word)
let words = ["apple", "banana", "grape", "strawberry", "kiwi"]
map
transforms elements into a new array.filter
removes elements that donโt meet a condition.reduce
combines elements into a single value.These functions allow you to write more concise and functional Swift code.
You are given a array of student scores (out of 100). Your task is to process this array using map, filter, and reduce to find out the average score of students who passed (scored 50 or more).
Steps to Complete:
map
to curve the scores by adding 5 extra points to each studentโs score.filter
to keep only the passing scores (50 or more).reduce
to calculate the average score of the passing students.Use the following input:
let scores = [45, 78, 89, 32, 50, 92, 67, 41, 99, 56]
[50, 83, 94, 37, 55, 97, 72, 46, 104, 61]
[50, 83, 94, 55, 97, 72, 104, 61]
(50 + 83 + 94 + 55 + 97 + 72 + 104 + 61) / 8 = 77
In this task, you will apply functional programming concepts in Swift using map
, filter
, and reduce
to process and analyze movie ratings data. You will perform multiple transformations and calculations on the data using these higher-order functions.
You are provided with a dictionary where:
let movieRatings: [String: ] = [
"Inception": [9, 8, 10, 7, 6, 9, 8],
"Interstellar": [10, 9, 10, 8, 7, 9],
"The Dark Knight": [10, 10, 9, 9, 8, 10, 9],
"Tenet": [7, 6, 8, 7, 5, 6, 7],
"Dunkirk": [8, 9, 7, 8, 7, 8]
]
mapValues
)
mapValues
instead of map
. This only extracts and transforms the values from the dictionary, leaving the keys intact. This means the new dictionary will have the same keys but new values; in this case, the new value is the average rating.filter
)
map
and reduce
)**
map
to get an array of tuples (title, averageRating)
, then reduce
to find the highest.filter
and reduce
)**
filter
to classify movies into different categories, then reduce
to count them.map
and reduce
)**
map
to extract the number of ratings per movie, then reduce
to sum them.map
, filter
, and reduce
Together)**
map
to create an array of tuples (title, averageRating)
.filter
to remove movies with an average rating below 8.0.reduce
to determine the movie with the highest rating.map
The map
function applies a transformation to each element in a array and returns a new array with the modified values.
The basic structure of map
looks like this:
let result = myArray.map { item in
return doSomethingTo(item)
}
map
:{ item in ... }
: This is a function that takes one parameter:
item
: The next value in the array.for
Loop in Python:numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for number in numbers:
squared_numbers.append(number * number)
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
map
in Swift:let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map { number in
return number * number
}
print(squaredNumbers) // Output: [1, 4, 9, 16, 25]
map
Use map
to double every number in an array. Print out the new array.
let numbers = [1, 3, 5, 7, 9]