Swift Array map() method
There is a method known as map()
in Swift which performs the actions on an array in one go. This article is a complete tutorial with examples of map()
and its functionality.
What does this method do?
This method is responsible for transforming an array by applying the same operation on every element of the array. It makes sense, right, instead of typing a long code, we can use map()
to work with all the elements of the array at the same time.
It takes one parameter transform and applies it to the given array and returns the updated one.
Demonstration
We are provided an array of integers-[1,2,3,4,5,6]
We need to add value or say 2 to each element.
The output should be a new array that contains elements by adding 2 in each element-[3, 4, 5, 6, 7, 8]
Starting the task by creating an array containing the above values-
let myarr=[1,2,3,4,5,6]
We have successfully created an array, now we need to use the map
method to transform it into the output expected array.
let transformedArray=myarr.map({$0+2})
We have added two to each element of the array using the above syntax of map(). We need to print the elements of the array as-
print(transformedArray)
Here we have tried to print the output on the screen.
Complete code
Here I have enclosed the complete code with output for better understanding-
let myarr=[1,2,3,4,5,6] let transformedArray=myarr.map({$0+2}) print(transformedArray)
Output-
[3, 4, 5, 6, 7, 8]
We have seen an example to work with integers. Can we do it in strings in the same way? The answer would be yes, we can transform an array of strings, by performing a particular operation on each element of an array as-
Demonstration-
Suppose we are given an array of strings, we need to remove its first character in one go. We would use map() method to do so-
let myarr=["Learning","-is","-my","-passion"] let transformedArray=myarr.map({$0.dropFirst()}) print(transformedArray)
You guessed the output right! It’s amazing! The output will be-
["earning", "is", "my", "passion"]
I hope this tutorial proves to be helpful for your doubt or at least you have learned a little from this blog. Thanks for reading!
Keep Coding
Leave a Reply