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.
arr.map(condition)
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.
The value returned is an array containing the transformed elements of the array arr
.
// create arrayslet 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 numbersprint(numbers.map({$0 % 2 == 0}))// 2. return countsprint(fruits.map({$0.count}))// 3. add letter "s"print(languages.map({$0 + "s"}))// 4. increate dates by 1000print(dates.map({$0 + 1000}))
numbers
array to return true
or false
if the elements are even numbers by invoking the map(_:)
method.map(_:)
method to return the length of the string elements.languages
through the map(_:)
method by adding the letter "s"
to each of its elements.dates
array by the map(_:)
method by increasing the date elements by 1000
.