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, given the following array: let numbers = [1, 2, 3, 4] We could use map() to transform those numbers so they are doubled, like this: let doubled = numbers.map { $0 * 2 } You can map whatever you want.
🌐
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.
People also ask

What does array map() do in Swift?
The map() function in Swift is used on arrays and other collections to perform operations on each element in the collection. It applies a function to all elements in the array and returns a new array with the transformed elements.
🌐
dhiwise.com
dhiwise.com › post › swift-map-array-simplifying-transformations-in-swift
Enhance Your Development Workflow with Swift Map Array
How to implement the map function in Swift iOS?
To implement the map function in Swift iOS, you apply the function to an array or equivalent sequence. First, you define the required transformation through a closure and attach it to the map function called on your array. For example, if you have let numbers = [1, 2, 3, 4, 5] and you want to double each number, you would implement the map function like so: let doubledNumbers = numbers.map { $0 * 2}.
🌐
dhiwise.com
dhiwise.com › post › swift-map-array-simplifying-transformations-in-swift
Enhance Your Development Workflow with Swift Map Array
What is the difference between compactMap and map in Swift?
The main difference between compactMap and map in Swift is how they handle optional values. The map function will include nil values in the transformed array, resulting in an array of optional elements. On the other hand, compactMap removes the nil results from the output array.
🌐
dhiwise.com
dhiwise.com › post › swift-map-array-simplifying-transformations-in-swift
Enhance Your Development Workflow with Swift Map 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 ...
🌐
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
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 - Beginner Friendly.Beginner Friendly12 hours12 hours ... 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 ...
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.

Find elsewhere
🌐
DhiWise
dhiwise.com › post › swift-map-array-simplifying-transformations-in-swift
Enhance Your Development Workflow with Swift Map Array
June 18, 2024 - For instance, consider the example of transforming an array of Ints into a String. Swift’s map function creates an array of transformed elements in a way that each integer converts into a string.
🌐
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.
🌐
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)
🌐
Swift by Sundell
swiftbysundell.com › basics › map-flatmap-and-compactmap
Map, FlatMap and CompactMap | Swift by Sundell
For example, we might transform a URL into a piece of data by performing a network request, and then transform that data into an array of models, which we then finally transform into a list-based UI.
🌐
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:
🌐
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 ...
🌐
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:
🌐
Educative
educative.io › answers › what-is-the-arraymap-function-in-swift
What is the array.map(_:) function in Swift?
The value returned is an array containing the transformed elements of the array arr. ... Lines 2 to 5: We create four arrays. Line 11: We transform the numbers array to return true or false if the elements are even numbers by invoking the map(_:) ...
🌐
CodeBurst
codeburst.io › swift-map-flatmap-filter-and-reduce-53959ebeb6aa
Swift — Map, FlatMap, Filter and Reduce | by Santosh Botre | codeburst
March 11, 2019 - When implemented on sequences: Flattens a collection of collections. Join Medium for free to get updates from this writer. ... Say, we have two arrays within an array that we would like to combine into a single array.
🌐
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.
🌐
Swiftunboxed
swiftunboxed.com › open-source › map
Map - Swift Unboxed
Wikipedia calls map a “higher-order function” which means it’s a function that takes a function as a parameter. Remember, closures are functions too! (Or maybe functions are closures too?) You could convert an array of Double to an array of Int using a closure:
🌐
LinkedIn
linkedin.com › pulse › swift-array-map-flatmap-compatmap-aviram-netanel
Swift - Array map, flatMap & compatMap
February 2, 2023 - Note that flatMap WONT WORK if some of the elements are arrays and others not... let flatMixedArr = ["a", ["b", "c"], ["d"]].flatMap({$0}) //["a", ["b", "c"], ["d"]] Now lets play with more complex stuff, lets say Person: ... and now if we want a list of the kids names - (and you can see the difference between map & flatMap)