What is the array.map(_:) function in Swift?
Overview
The map(_:) function is an array method in Swift that returns an array containing the results of mapping the given condition over the array’s elements.
Syntax
arr.map(condition)
Parameters
-
arr: This is the array we want to map. -
condition: This is the mapping condition. It is a closure that accepts an element of the arrayarras its parameter and returns a transformed value of the same or of a different type.
Return value
The value returned is an array containing the transformed elements of the array arr.
Example
// create arrayslet numbers = [2, 4, 5, 100, 45]let fruits = ["orange", "mango", "grape"]let languages = ["Swift", "Python", "Java", "C", "C++"]let dates = [2022, 2012, 1998, 1774]/*map arrays and transform*/// 1. check if even numbersprint(numbers.map({$0 % 2 == 0}))// 2. return countsprint(fruits.map({$0.count}))// 3. add letter "s"print(languages.map({$0 + "s"}))// 4. increate dates by 1000print(dates.map({$0 + 1000}))
Explanation
- Lines 2 to 5: We create four arrays.
- Line 11: We transform the
numbersarray to returntrueorfalseif the elements are even numbers by invoking themap(_:)method. - Line 14: We transform the array fruits using the
map(_:)method to return the length of the string elements. - Line 17: We transform the array
languagesthrough themap(_:)method by adding the letter"s"to each of its elements. - Line 20: We transform the
datesarray by themap(_:)method by increasing the date elements by1000.