Let's start with a single array, like:

Copylet raceResult = ["one", "two", "four"]

If we want to combine each element with an offset counting from 0, we can use Array.enumerated(), along with map.

Copylet numberedRaceResult = raceResult
    .enumerated()
    .map { offset, element in "\(offset). \(element)" }

for numberedResult in numberedRaceResult {
    print(numberedResult)
}

// Prints:
// 0. one
// 1. two
// 2. four

You can see that I didn't call print inside the closure passed to map. You can do this, but it kind of defeats the purpose of map (which is to create an equal-sized output array from the transformed elements of the input array), because the result would be unused. In that case, it makes more sense to just use a for loop or a call to forEach, like @Sh_Khan showed.

To handle a nested array, it's much the same. We can use the same logic as for one array, but apply it to each sub-array.

Copylet raceResults = [
    ["one", "two", "four"],
    ["two", "one", "five", "six"],
    ["two", "one", "four", "ten"],
    ["one", "two", "four"],
]

let numberedRaceResults = raceResults
    .enumerated()
    .flatMap { outterOffset, raceResult in
        raceResult
            .enumerated()
            .map { innerOffset, element in "\(outterOffset).\(innerOffset). \(element)" }
    }

for numberedResult in numberedRaceResults {
    print(numberedResult)
}

// Prints:
// 0.0. one
// 0.1. two
// 0.2. four
// 1.0. two
// 1.1. one
// 1.2. five
// 1.3. six
// 2.0. two
// 2.1. one
// 2.2. four
// 2.3. ten
// 3.0. one
// 3.1. two
// 3.2. four

You'll notice that I used flatMap on the outter array, instead of a simple map. You can change it back and forth and compare the result. In short, flatMap gives you a single flat array of string results, rather than an array of sub-arrays of strings.

Answer from Alexander on Stack Overflow
🌐
Hacking with Swift
hackingwithswift.com › example-code › language › how-to-use-map-to-transform-an-array
How to use map() to transform an array - free Swift example code and tips
May 28, 2019 - For example, you could convert an array of strings to be uppercase: let strings = ["John", "Paul", "George", "Ringo"] let uppercased = strings.map { $0.uppercased() } SPONSORED Join us for deep dives, hands-on workshops, and world-class speakers at try! Swift Tokyo on April 12th-14th – come and see why we're the world's largest Swift community event!
🌐
Programiz
programiz.com › swift-programming › library › array › map
Swift Array map() (With Examples)
// use map() and uppercased() to transform array var result = languages.map { $0.uppercased() } print("After:", result) ... In the above example, we have used the map() and uppercased() methods to transform each element of the languages array.
🌐
Cocoa Casts
cocoacasts.com › swift-essentials-1-how-to-use-swift-map-to-transforms-arrays-sets-and-dictionaries
How to Use Swift Map to Transform Arrays, Sets, and ...
Take a look at the example below. import Foundation let strings = Set([ "one", "two", "three" ]) let ints = strings.map { $0.count } print(ints) Run the contents of the playground to see the result. You can verify that the order of the elements is undefined if you run the contents of the playground ...
Top answer
1 of 2
1

Let's start with a single array, like:

Copylet raceResult = ["one", "two", "four"]

If we want to combine each element with an offset counting from 0, we can use Array.enumerated(), along with map.

Copylet numberedRaceResult = raceResult
    .enumerated()
    .map { offset, element in "\(offset). \(element)" }

for numberedResult in numberedRaceResult {
    print(numberedResult)
}

// Prints:
// 0. one
// 1. two
// 2. four

You can see that I didn't call print inside the closure passed to map. You can do this, but it kind of defeats the purpose of map (which is to create an equal-sized output array from the transformed elements of the input array), because the result would be unused. In that case, it makes more sense to just use a for loop or a call to forEach, like @Sh_Khan showed.

To handle a nested array, it's much the same. We can use the same logic as for one array, but apply it to each sub-array.

Copylet raceResults = [
    ["one", "two", "four"],
    ["two", "one", "five", "six"],
    ["two", "one", "four", "ten"],
    ["one", "two", "four"],
]

let numberedRaceResults = raceResults
    .enumerated()
    .flatMap { outterOffset, raceResult in
        raceResult
            .enumerated()
            .map { innerOffset, element in "\(outterOffset).\(innerOffset). \(element)" }
    }

for numberedResult in numberedRaceResults {
    print(numberedResult)
}

// Prints:
// 0.0. one
// 0.1. two
// 0.2. four
// 1.0. two
// 1.1. one
// 1.2. five
// 1.3. six
// 2.0. two
// 2.1. one
// 2.2. four
// 2.3. ten
// 3.0. one
// 3.1. two
// 3.2. four

You'll notice that I used flatMap on the outter array, instead of a simple map. You can change it back and forth and compare the result. In short, flatMap gives you a single flat array of string results, rather than an array of sub-arrays of strings.

2 of 2
1

Map is used to convert one bunch of type T into things of some other type, X. Like map these Ints to String?s. You should not use map for side-effects, like printing the values, or updating a database etc. It should be a pure function that takes an input and returns an output. "Map these A's into B's". Pure meaning the value of the function only depends on the input, nothing else like the current state of the world, and doesn't change the world either (like printing to the console), so for example, map these int's by the function that adds 2 to them.

In your example:

Copyvar raceResults = [["one","two","four"],["two","one","five","six"],["two","one","four","ten"],["one","two","four"]]

You have an array of "arrays of strings".

You can map that to an array of so long as you have a function that takes "array of string" and turns that into "something else"

Here you map it with the Identity function, the function that just returns its input, which is going to take an array of strings as input and return the exact same array of strings as output:

Copy   raceResults.map {
       return $0 // Returns first array 
   }

This does nothing, and the result is the exact same thing as raceResults.

If you want to iterate over all these elements then the function flatMap is handy:

CopyraceResults.flatMap { $0 }.forEach { print($0) }

flatMap is flatten, then map. Flattening an array of arrays is to return an array with all the things 'flattened' one level, so [[1, 2, 3], [4, 5, 6]] -> [1, 2, 3, 4, 5, 6], but the definition of what to flatten means depends on the type of container, for example flatMap on Optional means something else to flatMap on Array.

🌐
Codecademy
codecademy.com › docs › swift › arrays › .map()
Swift | Arrays | .map() | Codecademy
November 22, 2022 - In the example above, each element in the name array is lower-cased and placed into a new array named lowerCaseNames. Then, the name array is mapped over again and a new array is returned with the count of each element.
🌐
Apple Developer
developer.apple.com › documentation › swift › sequence › map(_:)
map(_:) | Apple Developer Documentation
Returns an array containing the results of mapping the given closure over the sequence’s elements.
Top answer
1 of 2
7

There are 2 similar key functions which perform similar operations, the basic purpose of which is to take an array and build another array from it:

func map(transform:(R)->T) -> [T] --- Map takes an array of elements of one type and converts it to an array of elements of (potentially) another type, by calling a transform function on each element in turn. So you can convert an array of Int's to an array of strings:

[1, 2, 3, 4].map { "\($0)" } // --> ["1", "2", "3", "4"]

func filter(predicate:(T)->Boolean) -> [T] -- Filter takes an array of elements and converts it to an array of elements of the same type, but only includes those elements for which predicate returns true. So you can filter an array of ints to leave only the even numbers:

[1, 2, 3, 4].filter { $0 % 2 == 0 } // --> [ 2, 4]

There are other variants, such as flatMap which takes [[T]] and turns it into [T] by iterating over the input and array and appending the contents of each array to an output array:

[ [1, 2], [3, 4]].flatMap() // --> [1, 2, 3, 4]

It's also worth nothing that the concept behind map is that, in simplistic terms, it can be used to map any input type to an output type, so you can define:

func <R, T> map(in:R?, transform:(R)->T) -> T?

for example, which would translate any optional input type into an optional output type given a function that translates the base type.

2 of 2
5

The problem is $0.state = .Flat is an assignment. It does not return a value. Try this:

wheels = wheels.map { w in
    w.state = .Flat
    return w
}

map does not replace anything. It projects each element from your array to a new array by applying the transformation block. You can choose to assign this new array to the old array, but otherwise it will not alter the original array.

🌐
Apps Developer Blog
appsdeveloperblog.com › home › swift › how to use map(_:) in swift. code examples.
How to Use map(_:) in Swift. Code Examples. - Apps Developer Blog
June 6, 2020 - For example, the code snippet below will iterate over each element in a dictionary and will return either dictionary key or value. ... let months = [1:"January", 2:"February", 3: "March", 4: "Aprial", 5: "May", 6: "June", 7: "July", 8: "August", ...
Find elsewhere
🌐
Hacking with Swift
hackingwithswift.com › plus › functional-programming › transforming-data-with-map
Transforming data with map() – Hacking with Swift+
Swift actually has another function power feature that benefits both transformed() and map() without any further work from us: we can use key path expressions as functions. This was introduced in Swift 5.2, and it means if you can write a key path such as \X.y then you can use that in place of functions that expect an X and return y. For example, \String.count can be used in places where you want to send in a string and get back the value of its count property. To put that into code, we could create an array of strings then use either map() or transformed() to create an array of integers containing the counts of those strings:
🌐
Bugfender
bugfender.com › blog › swift-arrays
Swift Arrays: Map, Filter, Reduce & Sort Explained | Bugfender
November 7, 2025 - They accept a transformative function as their argument and they return the transformed argument. To take a very simple example, let’s map an array of Ints to an array of Strings:
🌐
Sling Academy
slingacademy.com › article › swift-array-map-method-tutorial-examples
Swift array map() method: Tutorial & examples - Sling Academy
// define User struct struct User { let name: String let age: Int } // an array of dictionaries let users = [ ["name": "Sekiro", "age": 33], ["name": "The Demon King", "age": 999], ["name": "The Legendary Wolf", "age": 93], ] // use map() to create User objects from dictionaries let transformed = users.map { dict -> User? in if let name = dict["name"] as? String, let age = dict["age"] as? Int { return User(name: name, age: age) } else { return nil } } // print the result print(transformed) ... [Optional(main.User(name: "Sekiro", age: 33)), Optional(main.User(name: "The Demon King", age: 999)), Optional(main.User(name: "The Legendary Wolf", age: 93))] Next Article: Slicing Arrays in Swift: From Basic to Advanced (with Examples)
🌐
Medium
medium.com › @danielbanales › using-the-map-function-in-swift-to-transform-collections-69f34b0fc943
Using the Map Function in Swift to Transform Collections | by Daniel BR | Medium
January 10, 2023 - You probably don’t like the fact are optional and prefer to ignore the nil values; Swift already provides us with a standard way to achieve this, using the compactMap method. This method allows you to create an array, that discards nil values; thus, the type of the elements would never be optional. You can also chain methods to make more complex operations. In the above example, first, we convert the Strings to Integers, using compactMap to discard any possible nil values, and then we use map to multiply each element by 2.
🌐
DhiWise
dhiwise.com › post › swift-map-array-simplifying-transformations-in-swift
Enhance Your Development Workflow with Swift Map Array
June 18, 2024 - The function we pass as an argument ... array remains the same. For example, the identity function, which is a function that always returns its input, can be used in a Swift map function....
🌐
Use Your Loaf
useyourloaf.com › blog › swift-guide-to-map-filter-reduce
Swift Guide to Map Filter Reduce
May 1, 2018 - let squares4 = values.map {value in value * value} The in keyword separates the argument from the body of the closure. If you prefer you can go one step further and use the numbered arguments shorthand: ... The type of the results is not limited ...
🌐
Swift by Sundell
swiftbysundell.com › basics › map-flatmap-and-compactmap
Map, FlatMap and CompactMap | Swift by Sundell
What’s even better is that — since our hashtags function accepts a String as input, just like the closure we’re passing to map above — we can simply pass our hashtags function directly as an argument to map, and it will actually use that function as its transform closure: ... Pretty cool! However, the output we’re getting above is an array containing arrays of strings (or [[String]]), which is probably not what we want. We most likely want a “flat” array that just contains hashtags, without the nested arrays (or [String]).
🌐
Better Programming
betterprogramming.pub › mapping-in-swift-a6d6132a38af
Mapping in Swift. Map and compactMap are important higher… | ...
October 20, 2020 - compactMap: a function that returns an array with the non-nil results of mapping the closure over the collection’s elements
🌐
Brightec
brightec.co.uk › home › blog › how to filter, map, and reduce in swift
Swift Basics: Mapping, Filtering, and Reducing in Swift |… | Brightec
August 16, 2023 - From Swift 5.2, we're now able to use key paths in place of the closures above, so we can change the map to let userIds = users.map(\.id) compactMap is a special type of map that filters out any nil elements. This is helpful when your mapping function could fail and you want to ignore those failures e.g. converting an array of strings to an array of URLs (not all strings are valid URLs).
Top answer
1 of 3
25

In Swift as per Apple's definition,

map is used for returning an array containing the results of mapping the given closure over the sequence’s elements

whereas,  

forEach calls the given closure on each element in the sequence in the same order as a for-in loop.

Both got two different purposes in Swift. Even though in your example map works fine, it doesn't mean that you should be using map in this case.

map eg:-

let values = [1.0, 2.0, 3.0, 4.0]
let squares = values.map {$0 * $0}

[1.0, 4.0, 9.0, 16.0] //squares has this array now, use it somewhere

forEach eg:-

let values = [1.0, 2.0, 3.0, 4.0]
values.forEach() { print($0 * 2) }

prints below numbers. There are no arrays returned this time.

2.0

4.0

6.0

8.0

In short to answer your questions, yes the array generated from map is wasted and hence forEach is what you should use in this case.

Update:

OP has commented that when he tested, the performance was better for map compared to forEach. Here is what I tried in a playground and found. For me forEach performed better than map as shown in image. forEach took 51.31 seconds where as map took 51.59 seconds which is 0.28 seconds difference. I don't claim that forEach is better based on this, but both has similar performance attributes and which one to use, depends on the particular use case.

2 of 3
3

According to Apple Doc

.map

The map(_:) method calls the closure expression once for each item in the array. You do not need to specify the type of the closure’s input parameter, number, because the type can be inferred from the values in the array to be mapped.

.forEach(_:) Apple Doc

Calls the given closure on each element in the sequence in the same order as a for-in loop.

var myArray = [1,2,3,4]
var sampleArray = [1,2,3,4]
//myArray = myArray.forEach() { ($0 * 2) }//Not allowed
sampleArray = sampleArray.map() { ($0 * 2) }
print("sampleArray array is \(sampleArray)")//sampleArray array is [2, 4, 6, 8]
🌐
Medium
mehrdad-ahmadian.medium.com › understanding-map-flatmap-and-compactmap-in-swift-eacafc38fb61
Understanding map, flatMap, and compactMap in Swift | by Mehrdad Ahmadian | Medium
December 24, 2023 - The map function in Swift is a straightforward yet powerful tool for transforming arrays. It takes each element in an array, applies a given function, and returns a new array of the transformed elements.