The map() method transforms the array by applying the same operation to each element in the array.
Example
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()
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()
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.