The SWIFT essential function map you need to know

Source: Internet
Author: User
Tags closure

Map is not used in OC, but Swift is exceptionally well-disposed when dealing with arrays, thanks to the function of map;

Map function Arr.map (< #T # #transform: (int) throws, t## (int) throws, t#>) it gets a closure expression as a unique parameter, and each element in the collection is called once for that closure function. and returns the value mapped by the element (which can also be a different type of value). The specific mapping method and return value type are specified by the closure.

About Map,swift Developer Conference Tang Qiao has a speech about Monat, the interpretation of the map I feel very essence, map is to take a box apart, take out the elements inside the box, the elements inside the box to perform a series of operations, and then put back into the box such a process.

Here is an example of an execution of a map function:

Map method Let         array = [1,2,3,4] let        NewArray = array.map {(element:int)-string in let            string = string.in It (format: "%d", Element)            return string        }            print (NewArray) let        newArray2 = Array.map ({            "\ ($0+10)"        })        Print (NewArray2)

The element represents each of the elements in the array, the int is the initial type, the string is the type to be converted, and in the action method Newarrray returns an array of 4 strings ["1", "2", "3", "4"];

The following method is a closure of the form of an array of operations, an array of each element? 10 and then converted to a string; I hope you understand the closure of the package first;

Flatmap function

When it comes to map functions, it's natural to talk about Flatmap,flatmap and map functions, but there are other differences.

Map can do a map operation on all elements of a collection type. What about FlatMap?

Let numbers = [1, 2, 3]let Resultmap = Numbers.map ({$ 2}) print (Resultmap)//[3, 4, 5]let result = Numbers.flatmap {$ + 2}print (Result)//[3, 4, 5]

I can see that the values returned by the map and FLATMAP operations on numbers are exactly the same, which means that Flatmap also maps operations to arrays, but where is the difference?

Let numbers2 = [[1, 2, 3],[4, 5, 6]]let resultMap2 = Numbers2.map ({$0.map ({$ 2})}) print (RESULTMAP2)//[[3, 4, 5], [6, 7 , 8]]let resultFlatmap2 = Numbers2.flatmap ({$0.map ({$ 2})}) print (RESULTFLATMAP2)//[3, 4, 5, 6, 7, 8]

As can be seen, FlatMap still iterates through the elements of the array and executes the actions defined in the closures on those elements. But the only difference is that it makes the so-called "dimensionality Reduction" operation on the final result. Originally the original array is a two-dimensional, but after FlatMap, it becomes one-dimensional.

The specific principle can be queried for the definition of Flatmap, Flatmap function has a overload, and through the Result.append (contentsof:) The result element is added to the new array, become a one-dimensional array;

Another overload of the FlatMap
Let's look at an example:

Let Optionalarray: [String?] = ["AA", Nil, "BB", "CC"];var optionalresult = optionalarray.flatmap{$}print (optionalresul T)//["AA", "BB", "CC"]

So there is no error, and FlatMap return results, the original array is successfully filtered out of the nil value. Look more closely and you will find more. After using the FLATMAP call, all elements in the array are unpacked, and if you also use the Print function to output the original array, you will get the result:

Let Optionalarray: [String?] = ["AA", Nil, "BB", "CC"];var optionalresult = optionalarray.flatmap{$}print (optionalresul T)//["AA", "BB", "CC"]print (optionalarray)//[optional ("AA"), Nil, Optional ("BB"), Optional ("CC")]


That is, the type of the original array is [string] and the FlatMap call becomes [string]. This is also a significant difference between FLATMAP and map. If the same array, we use the map to invoke, get the output is this:

[Optional ("AA"), Nil, Optional ("BB"), Optional ("CC")]

This is the same as the original array. The difference between the two is that. The map function value transforms the element. It does not affect the structure of the array. The FLATMAP will affect the structure of the array. Before further analysis, let us take this understanding for the moment.

FlatMap This mechanism, it helps us to verify the data conveniently, for example, we have a set of image filenames, we can use FLATMAP to filter out invalid images:
How exactly does Flatmap filter out nil? I'd be interested to check it out for myself.

The SWIFT essential function map you need to know

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.