Map Function: Use map to loop over a collection and apply the same operation to each element in the collection. It returns an array always.
While learning ‘map’ function, I felt paucity of examples to clear the idea. Thought to document different examples I came through:
Example 1:
let values = [2.0,4.0,5.0,7.0]
let squares = values.map {$0 * $0}
print(squares)
Example 2:
let arrayOfNumbers = [1, 2, 3, 4]
let arrayOfString = arrayOfNumbers.map { "\($0)" }
print(arrayOfString) // Output: [“1”, “2”, “3”,“4”]
Example 3:
let scores = [0,28,124]
let words = scores.map {
NumberFormatter.localizedString(from: $0 as NSNumber, number: .spellOut)
}
print(words)// Output: [“zero”, “twenty-eight”, “one hundred twenty-four”]
Example 4:
let celcius = [-5.0, 10.0, 21.0, 33.0, 50.0]
let fahrenheit = celcius.map { $0 * (9/5) + 32 }
print(fahrenheit) // Output: [23.0, 50.0, 69.8, 91.4, 122.0]
Example 5:
let lengthInMeters: Set = [4.0,6.2,8.9]
let lengthInFeet = lengthInMeters.map {meters in meters * 3.2808}
print(lengthInFeet)
Here is a complete playground of the above code:
import UIKit
//Example 1
let values = [2.0,4.0,5.0,7.0]
let squares = values.map {$0 * $0}
print(squares)
//Example 2
let arrayOfNumbers = [1, 2, 3, 4]
let arrayOfString = arrayOfNumbers.map {"\($0)"}
print(arrayOfString)
// Output: [“1”, “2”, “3”,“4”]
//Example 3
let scores = [0,28,124]
let words = scores.map {
NumberFormatter.localizedString(from: $0 as NSNumber, number: .spellOut)
}
print(words)
// Output: [“zero”, “twenty-eight”, “one hundred twenty-four”]
//Example 4
let celcius = [-5.0, 10.0, 21.0, 33.0, 50.0]
let fahrenheit = celcius.map { $0 * (9/5) + 32 }
print(fahrenheit)
// Output: [23.0, 50.0, 69.8, 91.4, 122.0]
//Example 5
let lengthInMeters: Set = [4.0,6.2,8.9]
let lengthInFeet = lengthInMeters.map {meters in meters * 3.2808}
print(lengthInFeet)