You can use map() with an if-condition inside the closure:

var arr = [11, 12, 13, 14, 15]
arr = arr.map { elem in
    if elem == 15 { return 1 } else { return 0 }
}
print(arr) // [0, 0, 0, 0, 1]

Using the conditional operator ?: and closure shorthand notation $0, this can be simplified to

arr = arr.map { $0 == 15 ? 1 : 0 }

map() calls the closure with each element in turn, and returns an array with the closure return values. Inside the closure, $0 is the current argument, and the return value is 1 or 0, depending on the boolean condition.

Answer from Martin R on Stack Overflow
🌐
Educative
educative.io › answers › what-is-the-arraymap-function-in-swift
What is the array.map(_:) function in Swift?
The map(_:) function is an array method in Swift that returns an array containing the results of mapping the given condition over the array’s elements.
People also ask

What is the difference between CompactMap and map Swift?
- **compactMap**: Combines transformation and filtering. It applies a transformation to each element and discards any nil results, returning a new array with non-nil values. It's particularly useful when dealing with optionals and needing to both transform and filter data in one step. ```swift let optionalNumbers: [Int?] = [1, nil, 2, nil, 3] let nonNilNumbers = optionalNumbers.compactMap { $0 } // Output: [1, 2, 3] ``` ​ - **map**: Applies a transformation to each element and returns a new array with the transformed values. If the transformation results in optionals, map does not filter ou
🌐
dhiwise.com
dhiwise.com › post › how-to-choose-between-swift-filter-vs-compactmap
Swift filter vs compactMap: Understanding the Key Differences
What is the difference between map and filter in Swift?
In Swift, map and filter are both higher-order functions used for processing arrays, but they serve different purposes: - **map**: Transforms each element in an array based on a provided closure and returns a new array with the transformed elements. It doesn't change the number of elements in the array. For example, using map, you could convert an array of integers to their string representations. ```swift let numbers = [1, 2, 3] let strings = numbers.map { String($0) } // Output: ["1", "2", "3"] ``` - **filter**: Creates a new array containing only the elements that satisfy a given conditi
🌐
dhiwise.com
dhiwise.com › post › how-to-choose-between-swift-filter-vs-compactmap
Swift filter vs compactMap: Understanding the Key Differences
Is filter faster than for loop Swift?
The performance of filter compared to a for loop in Swift depends on the specific use case. - **filter**: Generally, filter is optimized for performance and is often more concise and readable than a for loop. Its time complexity is O(n), where n is the number of elements in the array. ```swift let numbers = [1, 2, 3, 4, 5] let evenNumbers = numbers.filter { $0 % 2 == 0 } ``` ​ - **for Loop**: A for loop provides more flexibility but might be less concise. It also has a time complexity of O(n) for similar operations, but the performance can vary based on how the loop is implemented and the
🌐
dhiwise.com
dhiwise.com › post › how-to-choose-between-swift-filter-vs-compactmap
Swift filter vs compactMap: Understanding the Key Differences
🌐
Use Your Loaf
useyourloaf.com › blog › swift-guide-to-map-filter-reduce
Swift Guide to Map Filter Reduce
May 1, 2018 - map returns an Array containing results of applying a transform to each item. filter returns an Array containing only those items that match an include condition. reduce returns a single value calculated by calling a combine closure for each ...
🌐
Programiz
programiz.com › swift-programming › library › array › map
Swift Array map() (With Examples)
In the above example, we have used the map() method to transform the numbers array. Notice the closure definition, ... This is a short-hand closure that multiplies each element of numbers by 3. $0 is the shortcut to mean the first parameter passed into the closure. Finally, we have stored the transformed elements in the result variable. // define array of Strings var languages = ["swift", "java", "python"] print("Before:", languages)
🌐
EDUCBA
educba.com › home › software development › software development tutorials › swift tutorial › swift map
Swift map | How Map Function works in Swift with Examples?
April 11, 2023 - Once the swift map function is used for iteration then it makes the function easy to manipulate. ... Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more. ... let rs_collction = i_p_collection.map { (elemnt_of_collection) -> Rslt_type in return transformed_data; } Where, rs_collction is the variable or storage variable which is used for storing the value into it with the variable to be defined into the frame cell.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Bugfender
bugfender.com › blog › swift-arrays
Swift Arrays: Map, Filter, Reduce & Sort Explained | Bugfender
November 7, 2025 - In the example, the extension is applied to Swift array with a constraint condition that the element type must be House. This means the summedAges method will only be available to arrays whose elements are of type House. Now, whenever we need to know the sum of ages in any Array of Houses in our app, we can simply write: ... We can do this with filters, maps...
🌐
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 strings = ... is undefined if you run the contents of the playground several times. It should be no surprise that Swift's map(_:) method can also be used to transform the keys and values of a dictionary....
Find elsewhere
🌐
Codingem
codingem.com › home › the map() function in swift
The map() Function in Swift - codingem.com
July 10, 2025 - In Swift, the map() function can be used to apply a function for each element in a collection. ... In this guide, you learn how to use the map() function with closures on different collection types in Swift.
🌐
DhiWise
dhiwise.com › post › how-to-choose-between-swift-filter-vs-compactmap
Swift filter vs compactMap: Understanding the Key Differences
August 14, 2024 - Understanding their practical differences can help you choose the right tool for your specific needs. Simple Conditional Filtering: Use filter when you need to create a new array with elements that meet a specific condition.
🌐
DEV Community
dev.to › eleazar0425 › map-filter-and-reduce-in-swift-mbk
Map, Filter and Reduce in Swift - DEV Community
June 16, 2020 - The filter function iterates over a collection and then returns a new array containing those elements that have matched our predicate condition.
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.

🌐
Swift
swift.org › blog › conditional-conformance
Conditional Conformance in the Standard Library | Swift.org
December 20, 2025 - In both, we search the base collection from the given index for the next separator. If there isn’t one, index(where:) returns nil for not found, so we use ?? endIndex to substitute the end index in that case. The only fiddly part is skipping over the separator in the index(after:) implementation, which we do with an optional map.
🌐
CodeBurst
codeburst.io › swift-map-flatmap-filter-and-reduce-53959ebeb6aa
Swift — Map, FlatMap, Filter and Reduce | by Santosh Botre | codeburst
March 11, 2019 - 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.
🌐
Hacking with Swift
hackingwithswift.com › plus › functional-programming › transforming-data-with-map
Transforming data with map() – Hacking with Swift+
And the result is a very flexible piece of code: one that applies to any kind of Sequence, one that can return any kind of data, and one that works with any kind of transformation function. Nice! Our transformed() function accepts a transformation function, and returns a new array containing each one of its items after they have been transformed. 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.
🌐
Swift Forums
forums.swift.org › using swift
Help with map function - Using Swift - Swift Forums
March 25, 2024 - I am observing a problem while using the map function on an Array; map keeps allocating memory and never returns. The problem can be reproduced with the following code, with two conditional code blocks A and B. @main enum MapTest { static func main () async throws { #if true // A let pointer: UnsafeMutablePointer let M = 8 pointer = .allocate(capacity: M) pointer.initialize(repeating: 5, count: M) print (pointer) print (poi...
🌐
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, the inputs for these functions are closures. ... The map() function applies a function to every item in a collection. Think of “mapping” or transforming one set of values into another set of values.
🌐
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 - let strings = ["John", "Paul", "George", "Ringo"] let uppercased = strings.map { $0.uppercased() } SPONSORED Your app’s website can drive a significant portion of downloads - but it needs to look good, be optimized, and stay up to date. AppView takes care of this, saving you time, headaches, and even money! ... This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
🌐
Medium
abhimuralidharan.medium.com › higher-order-functions-in-swift-filter-map-reduce-flatmap-1837646a63e8
Higher order functions in Swift: Filter, Map, Reduce, flatmap, compactMap | by Abhimuralidharan | Medium
May 22, 2024 - higher order functions in swift · The first two methods are of type (Double,Double)->Double . First one accepts two double values and return their sum . The second one returns the product of these two double values.
🌐
Swift by Sundell
swiftbysundell.com › basics › map-flatmap-and-compactmap
Map, FlatMap and CompactMap | Swift by Sundell
The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work. Let’s say that we’ve written a function that extracts any #hashtags that appear within a string, by splitting that string up into words, and then filtering those words to only include strings that start with the # character — like this: