Reprinted from: 1190000004050907Map
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.
It sounds a little complicated, but it's pretty simple. Imagine you have an array of type string:
let testArray = ["test1","test1234","","test56"]
map
The closure of a function receives a string (type string
) as a parameter because we call the function to handle the array element type String
. In this case, we want to return an integer array that corresponds to the character length of the member of the string element. Therefore, the return type of the closure is Int?
.
let anotherArray = testArray.map { (string:String) -> Int? in let length = string.characters.count guard length > 0 else { return nil } return string.characters.count} print(anotherArray) //[Optional(5), Optional(8), nil, Optional(6)]
FlatMap
flatMap
Much like a map
function, but it abandons the elements that are values nil
.
let anotherArray2 = testArray.flatMap { (string:String) -> Int? in let length = string.characters.count guard length > 0 else { return nil } return string.characters.count} print(anotherArray2) //[5, 8, 6]
The other map
is different from the function: If the element value is not nil, the flapMap
function can convert the optional type ( optional
) to a non-optional type ( non-optionals
).
Reference
image:@ fly_dragonfly/shutterstock.com
This article is translated by Swiftgg translation Group, has obtained the author's translation authorization, the latest article please visit http://swift.gg.
Swift--Map & FlatMap