How to use map() function in Swift

Using map() function we can transform each object of collection(list or array). The map() function returns an array after transforming each object of the list. Suppose you have an array of numbers as below.


let arrayNumbers = [1, 2, 3, 4, 5]

Now let’s suppose you want to add 5 to each object.


let transformedArray = arrayNumbers.map { $0 + 5 }
// output: [6, 7, 8, 9, 10]

Let’s multiply with 10 to each object


let newArray = arrayNumbers.map { $0 * 10 }
// output: [10, 20, 30, 40, 50]

Let’s suppose we have an array of names, and we want to convert names to lowercase.


let names = ["DAVID", "JOHN", "MILLER", "JACK"]
let lowerCasedNames = names.map { $0.lowercased() }
/*output: ["david", "john", "miller", "jack"]*/

So basically whenever you have to perform a similar action on each object you should use the map() function.

Using map() function we can event filter out any specific property of the object. For example, let’s suppose we have an array of wrestlers and we have to get an array of their names. Create a swift file and add below code.


class Wrestler {
    var name: String
    var age: Int
    var dob: String
    init(name: String, age: Int, dob: String) {
        self.name = name
        self.age = age
        self.dob = dob
    }
}

Now in your UIViewController class in viewDidLoad method create an array of wrestlers.


let john = Wrestler(name: "John Cena", age: 41, dob: "23 April 1977")
let undertaker = Wrestler(name: "The Undertaker", age: 54, dob: "24 March 1965")
let brock = Wrestler(name: "Brock Lesnar", age: 41, dob: "12 July 1977")

// Add these Wrestler into an array
let arrayWrestler = [john, undertaker, brock]

Using map() function we can get array of wrestler name.


let arrayNames = arrayWrestler.map { $0.name }
// output: ["John Cena", "The Undertaker", "Brock Lesnar"]

Leave a Reply

Your email address will not be published. Required fields are marked *