The map, Filter, Reduce for swift function programming

Source: Internet
Author: User
Tags closure

Use Map,Filter,Reduce to Array, dictionary, and other collection types in the Swift language (collection Type) may not be a habit for some people. For developers who have not been exposed to functional programming, the first reaction to processing data in a collection type may be to use a for in traversal. This article describes some of the new methods that can be used in swift.

Map

The Map function iterates through the collection type and makes the same operation for each element. The return value of Map is an array of the resulting results. For example: We are going to square the data inside an array, the common code is as follows:

let values: [Double]= [2.0,4.0,6.0,8.0]var squares: [Double] = []for value in values { squares.append(value * value)}

In the above code, we use the normal for -in traversal operation to square the elements in it, and then append the result of the calculation to a variable array. While the code in this section is well-done, we have more concise and secure code in Swift (the above squaers is a variable that may have unintended data modifications). Here's a look at the code to work with Map :

let values: [Double]= [2.0,4.0,6.0,8.0]let squares: [Double] = values.map{$0 * $0}

The code is not only more concise but squares is an immutable constant.

The closure syntax for the map function in the code above may be difficult for beginners to understand, with only one row of code that processes the data in the collection and eventually returns an array of results. For everyone to better understand the operation of the map above code can be rewritten as:

let values: [Double]= [2.0,4.0,6.0,8.0]let squares: [Double] = values.map({ (value: Double)-> Double in return value * value})

In this rewritten code, a Double parameter is passed in the closure, and a processing result of the same type is returned. Since map requires only one closure parameter, we can use the attribute of the mantissa closure to remove (), and the code inside the closure has only one row we can omit the return with the implicit return of the single expression:

let squares: [Double] = values.map{value in value * value}

The above value can also be replaced directly with the parameter abbreviation function of the closure:

values.map{$0 * $0}

The type of the element in the result array returned by the map operation does not require consistency with the original element type, for example, we can convert a common array of numbers into a corresponding word array:

let scores = [0,28,124]let words = scores.map { NSNumberFormatter.localizedStringFromNumber($0, numberStyle: .SpellOutStyle) }//["zero", "twenty-eight", "one hundred twenty-four"]

Of course the map operation can be applied in addition to the above Array,set and dictionary.

Filter

The Filter function iterates over the collection type and returns the element that satisfies the condition as an element in the result array. There is only one statement in the function that is conditional, and the closure iterates through the elements in the collection and puts together the results that satisfy the condition:

let digits = [1,4,10,15] let even = digits.filter { $0 % 2 == 0 } // [4, 10]
Reduce

The Reduce function combines all elements inside the collection type into a new value and returns. The parameters in reduce are two: an initial value, a combine closure. For example, the following code adds the elements in the array and the initial value is 10:

let items = [2.0,4.0,5.0,7.0] let total = items.reduce(10.0,combine: +) //28.0

Strings can be processed in addition to the above numeric types:

let codes = ["Big","nerd","coding"] let text = codes.reduce("", combine: +) // "Bignerdcoding"

The second parameter in reduce is a closure, and all you can do with a trailing closure is from my specific operation:

let codes = ["Big","nerd","coding"] let text = codes.reduce("v2ex") {text, name in "\(text),\(name)"}// "v2ex,Big,nerd,coding"
FlatMap

The function converts those multidimensional collection types to a one-dimensional collection type, with the following example:

let collections = [[5,2,7],[4,8],[9,1,3]] let flat = collections.flatMap { $0 } // [5, 2, 7, 4, 8, 9, 1, 3]

In addition, for the collection type of the optional type, the function can also remove the null value:

let codes: [String?] = ["Big",nil,"nerd",nil,"coding"] let values = codes.flatMap {$0} // ["Big","nerd","coding"]

The place that really embodies the power of FlatMap is combined with one of the above functions:

let collections = [[5,2,7],[4,8],[9,1,3]] let onlyEven = collections.flatMap { intArray in intArray.filter { $0 % 2 == 0 } }// [2, 4, 8]

The code above implements the filtering of the even numbers inside the multidimensional shaping array and combines them into an array. The argument to the FlatMap operation is a closure that takes an array of [INT] as a parameter. Of course we can also use implicit parameters to abbreviate them:

let collections = [[5,2,7],[4,8],[9,1,3]] let onlyEven = collections.flatMap { $0 in $0.filter { $0 % 2 == 0 } }// [2, 4, 8]

Note: The first and second in the preceding shorthand represent a word group similar to [5,2,7] in collections , while the third represents each integer in the Subarray

Instances that are combined with other operations:

//与map操作的组合以及简写let allSquared = collections.flatMap {     intArray in intArray.map { $0 * $0 } } // [25, 4, 49, 16, 64, 81, 1, 9]let allSquared = collections.flatMap { $0.map { $0 * $0 } }//与reduce操作的组合以及对等的组合操作let sums = collections.flatMap { $0.reduce(0, combine: +) }//对应的组合操作,两者结果是一样的let sums = collections.map { $0.reduce(0, combine: +) }
Chained combination

We have seen in the above flatMap closure can be combined with another operation. We can also make a reasonable combination of these operations outside the closure to achieve our goals. For example, sum all numbers in an array that are larger than a number:

let marks = [4,5,8,2,9,7] let totalPass = marks.filter{$0 >= 7}.reduce(0,combine: +) // 24

Or a square operation of a number inside an array and then filtering:

let numbers = [20,17,35,4,12] let evenSquares = numbers.map{$0 * $0}.filter{$0 % 2 == 0} // [400, 16, 144]
Summarize

The next time you want to iterate over the elements of the collection type and process each of them, you can first check to see if you can directly use the above actions or combine them.

Link:

The map, Filter, Reduce for swift function programming

The map, Filter, Reduce for swift function programming

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.