Since Swift 4 you can do @Tj3n's approach more cleanly and efficiently using the into version of reduce It gets rid of the temporary dictionary and the return value so it is faster and easier to read.

Sample code setup:

struct Person { 
    let name: String
    let position: Int
}
let myArray = [Person(name:"h", position: 0), Person(name:"b", position:4), Person(name:"c", position:2)]

Into parameter is passed empty dictionary of result type:

let myDict = myArray.reduce(into: [Int: String]()) {
    1.position] = $1.name
}

Directly returns a dictionary of the type passed in into:

print(myDict) // [2: "c", 0: "h", 4: "b"]
Answer from possen 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 - The map() method allows us to transform arrays (and indeed any kind of collection) using a transformation closure we specify.
🌐
Programiz
programiz.com › swift-programming › library › array › map
Swift Array map() (With Examples)
The map() method transforms the array by applying the same operation to each element in the array. The map() method transforms the array by applying the same operation to each element in the array. Example var numbers = [1, 2, 3, 4] // add 2 to each element var result = numbers.map({ $0 + 2}) ...
🌐
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.
🌐
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 ...
The map(_:) method has the ability to transform a sequence of elements. Let me show you what that means. We define a constant, strings, and assign an array of String objects to it.
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.

🌐
Hacking with Swift
hackingwithswift.com › plus › functional-programming › transforming-data-with-map
Transforming data with map() – Hacking with Swift+
It is generic, so that we can transform any kind of array into any other kind of array, and it’s also applied on Sequence so actually it also works on sets, dictionaries, and more. This function is so useful it comes baked right into Swift as map(), and it works almost identically to the function we built.
Find elsewhere
🌐
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 - Such as Arrays, Dictionaries, Sets, and Strings. The appropriate use of these methods results in easy-to-read operations, whereby they have often used an example of declarative programming. Swift contains many map methods, but in this article, we will focus on the most common ones, .map, .compactMap, and .flatMap. They will iterate each collection element through a closure, which receives the iterated element as an argument. You can return any object you want, considering that, in the end, you are creating an array whose generic type depends on what you are returning.
🌐
Codecademy
codecademy.com › docs › swift › arrays › .map()
Swift | Arrays | .map() | Codecademy
November 22, 2022 - The .map() method returns a new array containing the transformed values from calling the passed-in closure on each element of the given collection. It can be used on types that follow Swift’s Sequence and Collection protocols such as arrays, ...
🌐
Swift Forums
forums.swift.org › using swift
How to map Array/Dictionary data into custom observed object - Using Swift - Swift Forums
November 15, 2021 - Dear All, I try very hard to map Array/Dictionary data into a custom observed object and I need support. The custom input object: struct ImageAnnotation: Codable { let labelAnnotations: [LabelAnnotations] struct LabelAnnotations: Codable { let description: String let score: Double } } The which maps (the constant ist just a test): do { let annotateImageResponse = try!
🌐
Medium
lawrey.medium.com › swiftytutorial-map-properties-of-2-arrays-9da34c5e279d
Mapping properties of 2 arrays. Today, I will be sharing on the power… | by Lawrence Tan | Medium
July 5, 2017 - Today, I will be sharing on the power of high order functions in Swift which actually allow us to simply map an array of object A’s property to another property of each object B in another array.
🌐
DhiWise
dhiwise.com › post › swift-map-array-simplifying-transformations-in-swift
Enhance Your Development Workflow with Swift Map Array
June 18, 2024 - The map function’s syntax in Swift is straightforward: ... In the syntax, ‘element’ represents a single element in the array that we intend to transform. Once each array element goes through the map transformation, it results in a new array. Let's dismantle the working of Swift’s map function.
🌐
CodeBurst
codeburst.io › swift-map-flatmap-filter-and-reduce-53959ebeb6aa
Swift — Map, FlatMap, Filter and Reduce | by Santosh Botre | codeburst
March 11, 2019 - Swift has a number of collections like Objective-C has and all these Collection types are inherited from it Collection, like Array, Set, Dictionary for storing collections of values. The sequence is nothing but the iterator/traverse/retrieval from the first element to the last element without bothering about the element type. One of the very cool features of the Swift is a Higher Order Function. It has functions like map, flatMap, sort, filter and reduce which can be used on the collection types.
🌐
Swift by Sundell
swiftbysundell.com › basics › map-flatmap-and-compactmap
Map, FlatMap and CompactMap | Swift by Sundell
One way of performing such value transformations is by mapping a collection of values into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap.
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.

🌐
Bugfender
bugfender.com › blog › swift-arrays
Swift Arrays: Map, Filter, Reduce & Sort Explained | Bugfender
November 7, 2025 - There are three types of Maps methods in Swift arrays: the Map, the flatMap, and the compactMap. All of them are higher-order functions and they’re all commonplace in Swift. Maps are used to transform the elements of an array into different objects...
🌐
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 - In this example, we start with an instance of a struct and reduce the array in to it by incrementing the relevant property. let numbers = [1, 2, 3, 4, 5] struct OddEven { var odd = 0 var even = 0 } let oddEven = numbers.reduce(into: OddEven()) { result, number in if number % 2 == 0 { result.even += 1 } else { result.odd += 1 } } print(oddEven) // prints OddEven(odd: 3, even: 2) We hope you’ve found this post helpful. Now you should know a little more about mapping, filtering, and reducing in Swift.