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
🌐
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.

Discussions

How to map Array/Dictionary data into custom observed object - Using Swift - Swift Forums
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 ... More on forums.swift.org
🌐 forums.swift.org
0
November 15, 2021
Which is the easiest way to convert arrays into dictionaries in Swift?
let myArray = ["A", "B", "C", "D"] var dict = [String: Int]() for (index, value) in myArray.enumerated() { dict[value] = index } There are probably shorter ways, but I think that's the easiest. More on reddit.com
🌐 r/swift
18
0
April 24, 2022
Adding an index with functional methods like map, reduce, filter - Pitches - Swift Forums
Here's a quick draft pitch before I can expand on it. The gist is to add an index to the functional methods, so it can allow for something like (note mapi is used to differentiate it from map) let arrayNumbers = [1, 2, … More on forums.swift.org
🌐 forums.swift.org
0
June 17, 2018
How can I map an array without starting at the beginning of the array?
allAnimals[index...] is the subarray from index up. allAnimals[.. More on reddit.com
🌐 r/swift
4
0
February 5, 2023
🌐
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 - Swift version: 5.10 · Paul Hudson @twostraws May 28th 2019 · The map() method allows us to transform arrays (and indeed any kind of collection) using a transformation closure we specify.
🌐
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.
🌐
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.
🌐
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}) ...
Find elsewhere
🌐
Bugfender
bugfender.com › blog › swift-arrays
Swift Arrays: Map, Filter, Reduce & Sort Explained | Bugfender
November 7, 2025 - 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.
🌐
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!
🌐
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 › evolution › pitches
Adding an index with functional methods like map, reduce, filter - Pitches - Swift Forums
June 17, 2018 - Here's a quick draft pitch before I can expand on it. The gist is to add an index to the functional methods, so it can allow for something like (note mapi is used to differentiate it from map) let arrayNumbers = [1, 2, 3, 4, 5, 6] let oddOnes = arrayNumbers.mapi{(number, index) in if index % 2 == 0 { return number } else { return number * 2 } } in case of reduce, filter etc it can be used in a similar fashion where the index helps to eliminate loops that would ot...
🌐
DhiWise
dhiwise.com › post › swift-map-array-simplifying-transformations-in-swift
Enhance Your Development Workflow with Swift Map Array
June 18, 2024 - ... Swift array map is a highly valuable method due to its broad applicability and efficiency in sorting through large arrays. By using map arrays in Swift, developers can process arrays in a streamlined and readable manner.
🌐
Reddit
reddit.com › r/swift › how can i map an array without starting at the beginning of the array?
r/swift on Reddit: How can I map an array without starting at the beginning of the array?
February 5, 2023 -

I want to be able to take an array of items where each item has a Bool property, and condense it into an array that only contains the items where the Bool property is set to true.

However, I also want to be able to indicate which index in the original array that I want to start at. So, it would start at the index that I give, and put any items after that index into the new array first, but then go back to the start of the original array, and include the items that came before the index that I gave as well.

Here is an example that I just made in a Playground to demonstrate...

    import Foundation

    struct Animal {
        let name: String
        let hasLegs: Bool
    }

    struct AnimalsWithLegs {
        let animals: [Animal]
        
        init(allAnimals: [Animal], startingAt index: Int = 0) {
            //Need help here
            animals = allAnimals.compactMap { animal in
                if animal.hasLegs {
                    return animal
                } else {
                    return nil
                }
            }
        }
    }

    let animals = [
        Animal(name: "Dog", hasLegs: true),
        Animal(name: "Fish", hasLegs: false),
        Animal(name: "Cat", hasLegs: true),
        Animal(name: "Monkey", hasLegs: true),
        Animal(name: "Whale", hasLegs: false),
        Animal(name: "Turtle", hasLegs: true),
        Animal(name: "Shark", hasLegs: false),
        Animal(name: "Fox", hasLegs: true)
    ]

    let animalsWithLegs = AnimalsWithLegs(allAnimals: animals, startingAt: 4)

    for animal in animalsWithLegs.animals {
        print(animal.name)
    }

Currently, this example will print "Dog, Cat, Monkey, Turtle, Fox"

Those are all of the animals with legs from the array, so that's great.

However, since I gave a startingAt index of 4 when I called the AnimalsWithLegs() initializer, I would actually like it to print "Turtle, Fox, Dog, Cat, Monkey" instead.

How can I modify the AnimalsWithLegs() initializer to get this result?

🌐
Sarunw
sarunw.com › posts › different-ways-to-map-dictionary-in-swift
Different ways to map over Dictionary in Swift | Sarunw
September 11, 2023 - Dictionary.init(uniqueKeysWithValues:): You can create a new dictionary from an array of key-value pair Tuple with this initializer. We can use these two methods to transform the key of a dictionary. In this example, we transform each key to uppercase. let dict: [String: Int] = [ "a": 1, "b": 2, "c": 3 ] // 1 · let uppercasedKeyTuple = dict.map { (key, value) in return (key.uppercased(), value) } print(uppercasedKeyTuple) // [("C", 3), ("B", 2), ("A", 1)] // 2
🌐
Use Your Loaf
useyourloaf.com › blog › swift-guide-to-map-filter-reduce
Swift Guide to Map Filter Reduce
May 1, 2018 - Use map to loop over a collection and apply the same operation to each element in the collection. The map function returns an array containing the results of applying a mapping or transform function to each item:
🌐
Waldo
waldo.com › home › learn › mobile › understanding higher-order functions in swift
Understanding map, filter, reduce in Swift
January 27, 2026 - There are many higher order functions ... instead, let’s have a look at a commonly used higher order function; map. A map is always used to take a value of one type, and transform it into another value. For example, we could transform an array of [String] to [URL] as foll...
🌐
Swiftunboxed
swiftunboxed.com › open-source › map
Map - Swift Unboxed
January 25, 2017 - 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:
🌐
Appy Pie Vibe
appypievibe.ai › home › app development › map, reduce and filter in swift
Map, Reduce and Filter in Swift – Appy Pie Vibe
November 11, 2020 - In Swift you use map(), reduce() and filter() to loop over collections like arrays and dictionaries, without using a for-loop.