You can use enumerate to convert a sequence (Array, String, etc.) to a sequence of tuples with an integer counter and and element paired together. That is:

let numbers = [7, 8, 9, 10]
let indexAndNum: [String] = numbers.enumerate().map { (index, element) in
    return "\(index): \(element)"
}
print(indexAndNum)
// ["0: 7", "1: 8", "2: 9", "3: 10"]

Link to enumerate definition

Note that this isn't the same as getting the index of the collection—enumerate gives you back an integer counter. This is the same as the index for an array, but on a string or dictionary won't be very useful. To get the actual index along with each element, you can use zip:

let actualIndexAndNum: [String] = zip(numbers.indices, numbers).map { "\($0): \($1)" }
print(actualIndexAndNum)
// ["0: 7", "1: 8", "2: 9", "3: 10"]

When using an enumerated sequence with reduce, you won't be able to separate the index and element in a tuple, since you already have the accumulating/current tuple in the method signature. Instead, you'll need to use .0 and .1 on the second parameter to your reduce closure:

let summedProducts = numbers.enumerate().reduce(0) { (accumulate, current) in
    return accumulate + current.0 * current.1
    //                          ^           ^
    //                        index      element
}
print(summedProducts)   // 56

Swift 3.0 and above

Since Swift 3.0 syntax is quite different.
Also, you can use short-syntax/inline to map array on dictionary:

let numbers = [7, 8, 9, 10]
let array: [(Int, Int)] = numbers.enumerated().map { (1) }
//                                                     ^   ^
//                                                   index element

That produces:

[(0, 7), (1, 8), (2, 9), (3, 10)]
Top answer
1 of 6
475

You can use enumerate to convert a sequence (Array, String, etc.) to a sequence of tuples with an integer counter and and element paired together. That is:

let numbers = [7, 8, 9, 10]
let indexAndNum: [String] = numbers.enumerate().map { (index, element) in
    return "\(index): \(element)"
}
print(indexAndNum)
// ["0: 7", "1: 8", "2: 9", "3: 10"]

Link to enumerate definition

Note that this isn't the same as getting the index of the collection—enumerate gives you back an integer counter. This is the same as the index for an array, but on a string or dictionary won't be very useful. To get the actual index along with each element, you can use zip:

let actualIndexAndNum: [String] = zip(numbers.indices, numbers).map { "\($0): \($1)" }
print(actualIndexAndNum)
// ["0: 7", "1: 8", "2: 9", "3: 10"]

When using an enumerated sequence with reduce, you won't be able to separate the index and element in a tuple, since you already have the accumulating/current tuple in the method signature. Instead, you'll need to use .0 and .1 on the second parameter to your reduce closure:

let summedProducts = numbers.enumerate().reduce(0) { (accumulate, current) in
    return accumulate + current.0 * current.1
    //                          ^           ^
    //                        index      element
}
print(summedProducts)   // 56

Swift 3.0 and above

Since Swift 3.0 syntax is quite different.
Also, you can use short-syntax/inline to map array on dictionary:

let numbers = [7, 8, 9, 10]
let array: [(Int, Int)] = numbers.enumerated().map { (1) }
//                                                     ^   ^
//                                                   index element

That produces:

[(0, 7), (1, 8), (2, 9), (3, 10)]
2 of 6
11

For Swift 2.1 I wrote next function:

extension Array {

 public func mapWithIndex<T> (f: (Int, Element) -> T) -> [T] {     
     return zip((self.startIndex ..< self.endIndex), self).map(f)
   }
 }

And then use it like this:

    let numbers = [7, 8, 9, 10]
    let numbersWithIndex: [String] = numbers.mapWithIndex { (index, number) -> String in
        return "\(index): \(number)" 
    }
    print("Numbers: \(numbersWithIndex)")
🌐
Swift Forums
forums.swift.org › evolution › pitches
Adding an index with functional methods like map, reduce, filter - Pitches - Swift Forums
June 17, 2018 - The gist is to add an index to ... = [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 ...
🌐
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}) ...
🌐
Swiftunboxed
swiftunboxed.com › open-source › map
Map - Swift Unboxed
For standard arrays, the highest valid index is (count - 1) but we can’t count on that here. We usually think of size and index as linked, but they’re separate concepts for generic collections. To summarize: The index starts at startIndex and gets advanced with formIndex(after:).
🌐
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, sets, and dictionaries.
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.

Find elsewhere
🌐
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 ...
We invoke map(_:) on strings and pass a closure to the map(_:) method. The closure is executed for each element of the array and it accepts the element as its only argument.
🌐
Bugfender
bugfender.com › blog › swift-arrays
Swift Arrays: Map, Filter, Reduce & Sort Explained | Bugfender
November 7, 2025 - Creating a Swift extension for ... in Swift. To demonstrate how it works, let’s look at a practical example. We’re going to make an extension to fix an issue tha allt arrays have by default: not having a safe way of accessing an array element in a specific index position without ...
🌐
Reddit
reddit.com › r/swiftui › finding the index of an array element
r/SwiftUI on Reddit: Finding the index of an Array element
June 25, 2022 -

Hi everyone,

I am currently going through the tutorial to code the Scrumdinger Application which is an apple developer tutorial. I am struggling to understand what this highlighted line of code means and the code seems quite abstract although I have come across some bits like this before, and used it but not really understood what it meant.

To paint you a picture of what's involved, the speakers array contains speakers which each have a Boolean property and also an id which is a UUID. I have also tried to work out what the 'firstIndex(where:..) bit of code is doing. Pulling up its overview gives me this -

I'm not really sure what the predicate is in this case and what throwing a bool means, or even equatable. If you guys could help me gain a better understanding, maybe by saying what this Scrumdinger code is doing and what this Summary means in a few sentences in English, I would be very grateful. Also if you happen to know any applications or tutorials in which this type of code is used very regularly, or even Youtube tutorials, or just a key overarching topic name this would come under, I would embrace practicing this a lot to gain a better understanding.

Top answer
1 of 3
4
These two pieces of code do essentially the same thing: struct MyStruct { let name: String } let myArray = [MyStruct(name:"Able"), MyStruct(name: "Baker"), MyStruct(name: "Charlie")] if let firstIndex = myArray.firstIndex(where: {$0.name == "Baker"}) { print("Found at index: \(firstIndex)") } for i in 0..
2 of 3
3
So first of all, he chaining if's conditions, and checks whether the speaker.isCompleted property is true or false, *only* if it is true, it proceeds to the next if check, which is the 'firstIndex' part, now what you need to understand about 'firstIndex' is that it is returning an optional, so firstIndex is a function that you provide a condition and by that condition the function is iterating through the array in this case and looking for the first index of the element that stands in that condition. If nothing has been found, it will return nil, that's why you have to unwrap it, and that's why he used it in an 'if let' check. *$0* signifies the element that is being compared every iteration, that is basically the argument that has been passed. So in that case, $0 means a single speaker in every iteration( in an array of [speaker1,speaker2,speaker3], $0 in the first iteration will be speaker1, second iteration speaker2 ,and so on..) But you're also in a ForEach which gives you a 'speaker' variable, which also represents pretty much the same thing. So basically this whole if statement is to check whether there is a speaker with the property isCompleted equal to true, and if it there is, find its index and store it in the variable 'index'. Equatable is a Protocol, basically, every type that conforms to this protocol can be compared with the == or != . for an instance, Integers (3!=5 or 5==5). In your case, Speaker is a struct (I assume), and what they tell you on the docs, is that the Speaker struct doesn't have to conform to Equatable protocol to be able to use 'firstIndex', and find an element of that type. There is much more to it, this was just a brief explanation, I think you should read a book about swift or read the docs as now they are pretty nice tbh. If you're looking for a nice book, I suggest - Matt Neuburg - iOS 15 Programming Fundamentals with Swift_ Swift, Xcode, and Cocoa Basics-O'Reilly Media (2021) it pretty much covers all the fundamentals you need to know. Good luck mate, hope this helps.
🌐
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?

🌐
Sling Academy
slingacademy.com › article › swift-array-map-method-tutorial-examples
Swift array map() method: Tutorial & examples - Sling Academy
Overview In Swift programming, the array map() method is used for transforming an array by applying the same operation to each element of the array using a specified transformation closure. The syntax of the map() method...
🌐
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.
🌐
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 - When you have an array of arrays, you can flatten them into a simple array; that is precisely what flatMap does. You can use map methods in dictionaries, but the result will be an array.
Top answer
1 of 16
940

As swift is in some regards more functional than object-oriented (and Arrays are structs, not objects), use the function "find" to operate on the array, which returns an optional value, so be prepared to handle a nil value:

let arr:Array = ["a","b","c"]
find(arr, "c")!              // 2
find(arr, "d")               // nil

Use firstIndex and lastIndex - depending on whether you are looking for the first or last index of the item:

let arr = ["a","b","c","a"]

let indexOfA = arr.firstIndex(of: "a") // 0
let indexOfB = arr.lastIndex(of: "a") // 3
2 of 16
271

tl;dr:

For classes, you might be looking for:

let index = someArray.firstIndex{$0 === someObject}

Full answer:

I think it's worth mentioning that with reference types (class) you might want to perform an identity comparison, in which case you just need to use the === identity operator in the predicate closure:


Swift 5, Swift 4.2:

let person1 = Person(name: "John")
let person2 = Person(name: "Sue")
let person3 = Person(name: "Maria")
let person4 = Person(name: "Loner")

let people = [person1, person2, person3]

let indexOfPerson1 = people.firstIndex{$0 === person1} // 0
let indexOfPerson2 = people.firstIndex{$0 === person2} // 1
let indexOfPerson3 = people.firstIndex{$0 === person3} // 2
let indexOfPerson4 = people.firstIndex{$0 === person4} // nil

Note that the above syntax uses trailing closures syntax, and is equivalent to:

let indexOfPerson1 = people.firstIndex(where: {$0 === person1})


Swift 4 / Swift 3 - the function used to be called index

Swift 2 - the function used to be called indexOf

* Note the relevant and useful comment by paulbailey about class types that implement Equatable, where you need to consider whether you should be comparing using === (identity operator) or == (equality operator). If you decide to match using ==, then you can simply use the method suggested by others (people.firstIndex(of: person1)).

🌐
Charlieinden
charlieinden.github.io › ios-interviews › 2020-08-23_Deep-Dive-into-Map-Function-in-Swift-caba9d35d95f.html
Deep Dive into Map Function in Swift
As usual, all the code will be right here inline, but you can check out the current source in Collection.swift on GitHub. Looks pretty good! In our implementation, we set up an empty mutable array. Here, the standard library sets up a ContiguousArray directly. There are three flavors of array: ContiguousArray, ArraySlice, and Array. The differences are beyond the scope of this article but a contiguous array is like the textbook canonical array: a block of contiguous memory that you can index into.