Swift Array map()

The map() method transforms the array by applying the same operation to each element in the array.

Example

var numbers = [1, 2, 3, 4]

// add 2 to each element var result = numbers.map({ $0 + 2})
print(result) // Output: [3, 4, 5, 6]

map() Syntax

The syntax of the map() method is:

array.map(transform)

Here, array is an object of the Array class.


map() Parameters

The map() method takes one parameter:

  • transform - a closure body that describes what type of transformation is to be done.

map() Return Value

  • returns a new array that contains the transformed elements.

Example 1: Swift Array map()

var numbers = [1, 2, 3]

// multiply each elements by 3 var result = numbers.map { $0 * 3 }
print(result)

Output

[3, 6, 9]

In the above example, we have used the map() method to transform the numbers array. Notice the closure definition,

{ $0 * 3 }

This is a short-hand closure that multiplies each element of numbers by 3.

$0 is the shortcut to mean the first parameter passed into the closure.

Finally, we have stored the transformed elements in the result variable.


Example 2: Uppercase Array Of Strings Using map()

// define array of Strings
var languages = ["swift", "java", "python"]

print("Before:", languages)

// use map() and uppercased() to transform array var result = languages.map { $0.uppercased() }
print("After:", result)

Output

Before: ["swift", "java", "python"]
After: ["SWIFT", "JAVA", "PYTHON"]

In the above example, we have used the map() and uppercased() methods to transform each element of the languages array.

The uppercased() method converts each string element of an array to uppercase. And the converted array is stored in the result variable.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges