How to Use map(_:) in Swift. Code Examples.

In this short Swift tutorial, you will learn how to use one of the High Order Functions in Swift called map(_:) to apply a transformation to each element in an Array.

Given an Array of Names

Let’s consider an Array of String values:

let names = ["sergey", "michael", "john", "bill", "tom"]

All values in this Array of Strings start with a lower case letter and we know that names should start with a capital letter. Let’s see how we can use map(_:) function to transform each element in the above array and capitalize the first letter.

Transform Array with Map(_:). Example 1. 

One way of using the map(_:) function is this:

let names = ["sergey", "michael", "john", "bill", "tom"]
let capitalizedNames = names.map { (name) -> String in
    return name.capitalized
}

If we run the above code in Xcode playground we should get the following result:

["Sergey", "Michael", "John", "Bill", "Tom"]

Here is a screenshot of a complete example:

Transform Array with Map. Example 1.

Transform Array Map(_:). Example 2. 

Although the above code example works well there is a shorter way of transforming an element in Swift Array using map(_:) function. It will fit in a single line of code.

let names = ["sergey", "michael", "john", "bill", "tom"]
let capitalizedNames = names.map { $0.capitalized }

If we run this code example, the output will be exactly the same. Below is a screenshot of the Xcode playground that demonstrates how it works.

Transform Array Map(_:). Example 2.

Use Map to Iterate Dictionary

You can also use map(_:) function with dictionaries. For example, the code snippet below will iterate over each element in a dictionary and will return either dictionary key or value.

Iterate over a dictionary and return keys only

let months = [1:"January", 2:"February", 3: "March", 4: "Aprial", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "Noveber", 12: "December" ]

let monthDictionaryKeys = months.map { (key, value) -> Int in
    return key
}

print(monthDictionaryKeys)

Iterate over a dictionary and return values only 

let months = [1:"January", 2:"February", 3: "March", 4: "Aprial", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "Noveber", 12: "December" ]

let monthDictionaryValues = months.map { (key, value) -> String in
    return value
}

print(monthDictionaryValues)

I hope this short tutorial was helpful to you. This website contains many other Swift code examples and video tutorials. Have a look around and I hope you will find them helpful.


Leave a Reply

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