Overview
Swift's map method transforms every element in a sequence and returns a new array with the transformed values. Instead of creating an empty array, looping through the original data, and appending each new value, you describe the transformation in one place.
Use map when you want the same number of items, but each item needs to become something else. That might mean doubling numbers, capitalizing names, pulling titles out of model objects, or formatting values for a SwiftUI view.
Basic Syntax
The closure you pass to map receives each element and returns the transformed value for the new array.
let transformedArray = array.map { item in
return transformedValue
}The transformed value can be the same type as the original element, or it can be a completely different type.
From Loop to Map
Here is the kind of loop that map is designed to replace:
let numbers = [1, 2, 3, 4]
var doubledWithLoop: [Int] = []
for number in numbers {
doubledWithLoop.append(number * 2)
}
let doubledWithMap = numbers.map { number in
number * 2
}
print(doubledWithMap)Both approaches produce [2, 4, 6, 8], but the map version focuses on the transformation instead of the mechanics of building the array.
Using Shorthand Syntax
For short transformations, Swift's shorthand argument name $0 keeps the code compact.
let numbers = [1, 2, 3, 4]
let doubled = numbers.map { $0 * 2 }
print(doubled)Use shorthand when the closure is easy to read at a glance. If the transformation is longer, a named parameter is often clearer.
Transforming to a Different Type
map does not have to return the same type it receives. This example converts integers into strings.
let scores = [80, 95, 72]
let labels = scores.map { score in
"Score: \(score)"
}
print(labels)The original array is [Int], but the mapped result is [String].
Mapping Strings
Because strings are values too, you can transform arrays of strings the same way.
let names = ["alice", "bob", "maya"]
let displayNames = names.map {
$0.capitalized
}
print(displayNames)This is useful when preparing user-facing labels from raw data.
Mapping Custom Structs
In app code, you often map arrays of model objects into one property you need for display or processing.
struct Task {
let title: String
let isComplete: Bool
}
let tasks = [
Task(title: "Study map", isComplete: false),
Task(title: "Build app", isComplete: true)
]
let taskTitles = tasks.map { task in
task.title
}
print(taskTitles)The result is an array of titles: ["Study map", "Build app"].
Preparing Data for SwiftUI
A common SwiftUI use case is turning model data into strings or lightweight view data.
struct Workout {
let name: String
let steps: Int
}
let workouts = [
Workout(name: "Morning Walk", steps: 10423),
Workout(name: "Lunch Run", steps: 6420)
]
let rows = workouts.map { workout in
"\(workout.name): \(workout.steps) steps"
}You still keep your source data intact, but you can derive the exact display values you need.
Using a Named Function with Map
If you already have a function that transforms one value, you can pass the function directly to map.
func priceWithTax(_ price: Double) -> Double {
price * 1.13
}
let prices = [9.99, 24.99, 49.99]
let withTax = prices.map(priceWithTax)
print(withTax)This keeps reusable transformation logic in one function while still giving you the concise mapping call.
When to Use compactMap
Use compactMap when the transformation can return nil and you want to remove those nil values from the result.
let strings = ["1", "two", "3", "four", "5"]
let numbers = strings.compactMap {
Int($0)
}
print(numbers)The result is [1, 3, 5]. Values that could not be converted to integers are skipped.
When to Use flatMap
Use flatMap when each element produces a sequence and you want one flattened result.
let groups = [[1, 2], [3, 4], [5]]
let allNumbers = groups.flatMap {
$0
}
print(allNumbers)The result is [1, 2, 3, 4, 5] instead of an array of arrays.
Using map with Optionals
Optionals also have a map method. It transforms the wrapped value only when the optional contains a value.
let username: String? = "chris"
let displayName = username.map {
$0.capitalized
}
print(displayName as Any)If username were nil, the result would also be nil.
Common Mistakes
Expecting map to change the original array
map returns a new array. It does not mutate the original collection.
Using map when compactMap is needed
If your closure returns optionals and you want to remove nil results, reach for compactMap.
Writing a loop that only builds a transformed array
If your loop starts with an empty array and appends one transformed value for every original element, it is probably a good candidate for map.
Confusing map with filter
map transforms values. filter keeps or removes values based on a condition.
Quick Reference
| Syntax | What It Does |
|---|---|
array.map { $0 * 2 } | Transforms each number by doubling it |
array.map { $0.uppercased() } | Transforms each string to uppercase |
array.map { "Score: \($0)" } | Builds a string for each value |
array.map { item in item.property } | Pulls one property from each item |
array.compactMap { Int($0) } | Transforms values and removes nil results |
array.flatMap { $0 } | Flattens nested sequences into one array |
optional.map { transform } | Transforms the wrapped value when it exists |
array.map(functionName) | Uses a named function as the transformation |
Summary
mapreturns a new array by transforming every element.- The original array is not modified.
- The result can contain the same type or a different type.
- Use
$0for short, readable transformations. - Use named parameters when the closure needs more clarity.
- Use
compactMapwhen transformations can produce nil values that should be removed. - Use
flatMapwhen you want to transform and flatten nested sequences.
A helpful way to remember map is this: one input element becomes one output element. Once you spot that pattern in a loop, you can usually make the code shorter and clearer with map.