Examples of map function in Swift
Map function: use map to loop over a collection and apply the same operation to each element. It always returns an array.
While learning map, I felt a paucity of examples to make the idea click, so I documented a few different cases I came across.
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 celsius = [-5.0, 10.0, 21.0, 33.0, 50.0]
let fahrenheit = celsius.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's a complete playground with all of the above:
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 celsius = [-5.0, 10.0, 21.0, 33.0, 50.0]
let fahrenheit = celsius.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)