Swift--Map & FlatMap

Source: Internet
Author: User
Tags closure

Reprinted from: 1190000004050907Map

mapA 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"]

mapThe 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

flatMapMuch 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.