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 array arr as 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 arrays
let 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 numbers
print(numbers.map({$0 % 2 == 0}))
// 2. return counts
print(fruits.map({$0.count}))
// 3. add letter "s"
print(languages.map({$0 + "s"}))
// 4. increate dates by 1000
print(dates.map({$0 + 1000}))

Explanation

  • Lines 2 to 5: We create four arrays.
  • Line 11: We transform the numbers array to return true or false if the elements are even numbers by invoking the map(_:) 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 languages through the map(_:) method by adding the letter "s" to each of its elements.
  • Line 20: We transform the dates array by the map(_:) method by increasing the date elements by 1000.

Free Resources