Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
map
swift
communitycreator

What is the array.map(_:) function in Swift?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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}))
Transforming array elements using the map(_:) method

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.

RELATED TAGS

array
map
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring