Map and Flatmap are common concepts in functional programming and are available in languages such as Python. The map and FLAPMAP functions make it easy to convert an array into another new array.
Map a function can be called by an array, which takes a closure as a parameter, acting on each element in the array. The closure returns a transformed element, followed by a new array of all the transformed elements.
Simply put, map is a mapping function that maps a set into another set.
Swift's flatMap is not easy to understand, andFlatMap is much like the map function, but it abandons those elements that have a value of nil .
flatMap
is to handle a container rather than an array, so that you can better understand it.
To handle an optional type,FlatMaphave been overloaded. It takes an array of an optional type and returns a wrapped one that has noNilAn array of optional types of values.
Here is the definition of Flatmap
Extension Sequencetype {/// Return an ' Array ' containing concatenated results of mapping ' transform '///over ' SE LF '. Func flatmap<s:sequencetype> (@noescape Transform: (Self.Generator.Element), S), [s.generator.element] }extension Sequencetype {/// Return an ' Array ' containing the non-nil results of mapping ' transform '///over ' SE LF '. Func flatmap<t> (@noescape Transform: (Self.Generator.Element)-T), [t]}
Refer to the following sample code:
Let test1 = (1...7). map{(I:int), String? In return i > 1? String ("SSS \ (i)"): Nil}print (test1) Let test2 = (1...7). flatmap{(I:int), string? In return i > 1? String ("SSS \ (i)"): Nil}print (Test2)
Execution results
[Nil, Optional ("SSS 2"), Optional ("SSS 3"), Optional ("SSS 4"), Optional ("SSS 5"), Optional ("SSS 6"), Optional ("SSS 7")]
["SSS 2", "SSS 3", "SSS 4", "SSS 5", "SSS 6", "SSS 7"]
Reference articles
http://swift.gg/2015/08/06/swift-2-flatmap/
1190000004050907
Understanding the role of map and Flatmap to collections in Swift