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.

Answer from David Berry 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.
🌐
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.
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
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
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
🌐
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. Example var numbers = [1, 2, 3, 4] // add 2 to each element var result = numbers.map({ $0 + 2}) print(result) // Output: [3, 4, 5, 6] map() Syntax The syntax of the map() method is:
🌐
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 - 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.
🌐
Swift by Sundell
swiftbysundell.com › basics › map-flatmap-and-compactmap
Map, FlatMap and CompactMap | Swift by Sundell
We could also use plain map, which requires us to produce a non-optional value, for example by using a default: func convertToInt(_ string: String?) -> Int? { return string.map { Int($0) ?? 0 } } Swift’s various map functions are great to keep in mind when we need to transform sequences, or optionals, into a new form.
🌐
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 ...
import Foundation let countries = [ "US": "United States", "BE": "Belgium", "CN": "China" ] let ints = countries.mapValues { $0.count } print(ints) What Are the Benefits of the Final Keyword in Swift
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
🌐
Hacking with Swift
hackingwithswift.com › plus › functional-programming › transforming-data-with-map
Transforming data with map() – Hacking with Swift+
Swift actually has another function ... 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 ...
🌐
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)
🌐
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.
🌐
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:
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.

🌐
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 ...
🌐
Swiftunboxed
swiftunboxed.com › open-source › map
Map - Swift Unboxed
As usual, all the code will be right here inline, but you can check out the current source in Collection.swift on GitHub. public func map<T>(_ transform: (Iterator.Element) throws -> T) rethrows -> [T] {
🌐
Donny Wals
donnywals.com › map-flatmap-and-compactmap-in-swift-explained-with-examples
Map, flatMap and compactMap in Swift explained with examples
July 7, 2025 - The slightly more complicated sibling of map is called flatMap. You use this flavor of map when you have a sequence of sequences, for instance, an array of arrays, that you want to "flatten". An example of this is removing nested arrays so you end up with one big array.
🌐
DhiWise
dhiwise.com › post › exploring-the-intricacies-of-swift-map-dictionary
The Ultimate Swift Map Dictionary Tutorial for Beginners
July 10, 2024 - In the above example, the Swift dictionary map function transforms both the key and value of each element in the input dictionary by mapping the value to value+1 while keeping the same keys.
🌐
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
The map(_:) function loops over ... items, to which the operation was applied. In this example, map is used first to convert the names in the array to lowercase strings and then to count their characters....
🌐
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 - Swift, Apple’s powerful and intuitive programming language, has a rich set of features that make it a favorite among iOS and macOS developers. Among these features are three higher-order functions that are essential for efficient array manipulation: map, flatMap, and compactMap. In this article, we'll dive into each of these functions, explore their uses, and see them in action with practical examples...
🌐
Esri Developer
developers.arcgis.com › swift › maps-2d › tutorials › display-a-map
Display a map | ArcGIS Maps SDK for Swift | Esri Developer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 import SwiftUI import ArcGIS · Add a @State property wrapper named map of type Map with a default value.
🌐
Codecademy
codecademy.com › docs › swift › arrays › .map()
Swift | Arrays | .map() | Codecademy
November 22, 2022 - Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store. ... A powerful programming language developed by Apple for iOS, macOS, and more. 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 over again and a new array is returned with the count of each element.