In this new series on Swift code topics, descriptions of various basic features of the Swift programming language will be explored with examples of code. I use Xcode playgrounds for most of my prototype code development since that platform fosters exploration. The code examples used in this post have been uploaded to GitHub.
Since its introduction to the Apple development platform in 2014 (announced at WWDC 2014), Swift continues to mature rapidly due to its open development community (Swift.org). As such, Swift code is cleaner to write, is strongly typed, compiles to a fast executable, and includes many safe design principles.
In this post, the methods (map, flatMap, compactMap, and filter) are examined.
The map(_:) method applies a function on each item in a collection, essentially mapping one set of values to another set of values of possibly a different type. The map method is defined for a collection type (e.g., Dictionary, Set, Array), not just Arrays.
The first example squares the value of each integer value:
The second example converts an array of Fahrenheit temperatures to an array of Celsius temperatures:
The third example converts the array of numbers to an array of strings:
The flatMap(_:) method flattens a collection of collections into a collection.
An array of arrays is flatten to an array in the following example:
The compactMap(_:) method provides a convenient way to strip nil values from a collection (e.g., array).
The nil value result from an Int() conversion is stripped out of the array in the following example:
The filter(_:) method applies a condition to the values of a collection type. Only the values that satisfy the condition are included in the resultant collection type.
The following example extracts the values from an array that are modulo 2:
Map, FlatMap, and CompactMap by John Sundell.
Transforming collections in Swift by John Sundell.
Inside the Standard Library: Sequence.map() by Paul Hudson.
How To: Map, Reduce, and Filter in Swift by Reinder de Vries.
Swift Guide to Map Filter Reduce by Keith Harrison.
Swift – Map, FlatMap, Filter, and Reduce by Santosh Botre.
The Xcode logo is a copyright and trademark of Apple.
The CocoaPods logo is a copyright and trademark of CocoaPods.