The swift language has very many functional programming features. Common Map,reduce,filter have, at first glance and Python almost the same, under the introduction below
Closure Description:
Closures are self-contained functional code blocks that can be used in code or used as parameter values.
If we need two functions, one to calculate the average of the squares of two numbers, and one to calculate the average of the two-digit cubic, the traditional workaround would be this:
code
func Square (a:float), float {return a * A}func cube (a:float), float {return a * a * a}func averagesumofsquare S (a:float,b:float), float {return (square (a) + square (b))/2.0}func Averagesumofcubes (a:float,b:float), float {return (cube (a) + cube (b))/2.0}
We notice that the only difference between averagesumofsquares and Averagesumofcubes is simply to call the square or cubic function separately.
If I can define a general function. This function takes two numbers and a function that uses these two numbers as a parameter to calculate the average instead of repeating the call will be very good, we can use closures as function parameters
func averageoffunction (a:float,b:float,f: (float, float)), float {return (f (a) + f (b))/2}averageoffunction (3, 4, Square) averageoffunction (3, 4, Cube)
There are many ways to define a closure expression in swift. Here is the most verbose start to show to the most concise so far:
Code
averageOfFunction(3, 4, {(x: Float) -> Float in return x * x})averageOfFunction(3, 4, {x in return x * x})averageOfFunction(3, 4, {x in x * x})averageOfFunction(3, 4, {$0 * $0})
Map
In Swift, map is a method of the array class. We can use it to convert each element of an array.
Method:func map(transform: (T) -> U) -> U[]
If a string conversion is required for an int array today. Then you can use the map method:
let intArray = [1,111,1111]//结果为["1","11","111"]let stringArray = intArray.map({ (intValue) -> String in return "\(intValue)"})
Filter
filter is used to select elements in an array element that satisfy a certain condition.
Method:filter(includeElement: (T) -> Bool) -> T[]
Or the code on the map above continues to write:
//结果[111,1111]let filterArray = intArray.filter { (intValue) -> Bool in return intValue > 30}
Reduce
The reduce method computes the combination of array elements into a single value.
Method:reduce(initial: U, combine: (U, T) -> U) -> U
The code then reads:
//结果1223let sum = intArray.reduce(0,combine: +)let sum2 = intArray.reduce(0) { (int, int2) -> Int in return int+int2}
Introduction to Swift High-order functions (closures, MAP, Filter, Reduce)