Swift Syntax-Higher order function _swift Foundation

Source: Internet
Author: User
Tags instance method

Higher-order function Map,flatmap,reduce,filter can simplify the amount of code, can be used.


1, the map function, is the set and the String class instance method, the function is the diachronic modification Item;map does not modify the instance value, and creates a new copy.

Excerpted from official documents:

let-cast = ["Vivien", "Marlon", "Kim", "Karl"] let
lowercasenames = cast.map {$0.lowercased ()}
//' Lowercasename s ' = = ["Vivien", "Marlon", "Kim", "Karl"] let
lettercounts = cast.map {$0.count}
//' lettercounts ' = [6, 6, 3, 4]

2 more examples: 1, convert an int array to a string array, that is, the map supports converting array parameter types;

2, even times 10, testing the duration of the add custom logic;

    Let-array = [1, 2, 3] let
    str1 = Array.map ({"$\ ($)}")//array each element is converted to a string type let
    str2 = array.map{param-> Int i n   //traversal can add conditional judgment logic
        if param%2 = = 0 {return
            param */  /even multiplied by
        } else {return
            param
        }
    print (Array)//[1 2 3]
    print (STR1)//["$", "$"  , "$"
    print (STR2)  //[1,20,3]

2, Flatmap, function is similar to map, the difference is that Flatmap will filter nil elements and unpack optional.

Example:


ARR1 contains 5 values, ARR4 contains 4 values.

Flatmap can also convert multidimensional arrays into one-dimensional arrays;


For an n-dimensional array, the map function still returns an n-dimensional array.

The Ps:arr array contains 3 elements, and the map loops 4 times.


3, the filter function, as the name implies is to filter out the elements that meet the conditions.



4, reduce function, it can use 2 parameters that is $ and $, and the first 3 functions can only use one parameter of $.

Reduce can achieve a sum, or filter out the sum of the eligible records calculation.



Higher-order functions can also be chained to use (multilevel):

    Let-array = [1, 2, 3, 4, 5] let
    SUM0 = array.filter{$ > 2}.reduce (0, +)
    print (SUM0)  //12
Find the sum of the values in the array that are greater than 2.


Combined Call:

Finds all the even numbers in a two-dimensional array.

Let-array = [[1,2,3], [4,5,6], [7,8,9]] let
even = array.flatmap {$0.filter  
    {$0%2 = 0}
}
print (even) 
  //[2,4,6,8]

If you use a basic two-dimensional array to traverse the syntax is more trouble:

Basic two-dimensional array traversal
var Evenarr = [Int] () for
arr in array {for
    item in arr {
        if item% 2 = 0 {
            Evenarr.appe ND (item)}}
print (Evenarr)







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.