Swift高階函數介紹(閉包、Map、Filter、Reduce)

來源:互聯網
上載者:User

標籤:相同   bin   radius   reduce   map   border   render   元素   geo   

Swift語言有非常多函數式編程的特性。常見的map,reduce,filter都有,初看和python幾乎相同,以下簡介下


閉包介紹:

閉包是自包括的功能代碼塊,能夠在代碼中使用或者用來作為參數傳值。

如果我們須要兩個函數,當中一個計算兩個數的平方的平均值,還有一個計算兩個數的立方的平均值,傳統的解決方案會是這樣:

代碼
func square(a:Float) -> Float { return a * a}func cube(a:Float) -> Float { return a * a * a}func averageSumOfSquares(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}

我們注意到averageSumOfSquares和averageSumOfCubes的唯一不同僅僅是分別調用平方函數或立方函數。

如果我能夠定義一個通用函數。這個函數以兩個數和一個使用這兩個數的函數作為參數,來計算平均值而不是反覆調用將會非常好,我們能夠使用閉包作為函數參數

代碼
func averageOfFunction(a:Float,b:Float,f:(Float -> Float)) -> Float { return (f(a) + f(b)) / 2}averageOfFunction(3, 4, square)averageOfFunction(3, 4, cube)

在Swift中有非常多種定義閉包運算式的方法。這裡從最囉嗦的開始展示到最簡潔的為止:

代碼
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

在Swift中Map是Array類的一個方法。我們能夠使用它來對數組的每一個元素進行轉換。
方法:func map(transform: (T) -> U) -> U[]
假如如今須要對一個Int數組進行字串轉換。那麼就能夠使用map方法:
let intArray = [1,111,1111]//結果為["1","11","111"]let stringArray = intArray.map({ (intValue) -> String in return "\(intValue)"})

Filter

filter用於選擇數組元素中滿足某種條件的元素。


方法:filter(includeElement: (T) -> Bool) -> T[]
還是接著上面Map的代碼繼續寫:
//結果[111,1111]let filterArray = intArray.filter { (intValue) -> Bool in return intValue > 30}

Reduce

reduce方法把數組元素組合計算為一個值。
方法:reduce(initial: U, combine: (U, T) -> U) -> U
代碼接著上面寫:
//結果1223let sum = intArray.reduce(0,combine: +)let sum2 = intArray.reduce(0) { (int, int2) -> Int in return int+int2}



Swift高階函數介紹(閉包、Map、Filter、Reduce)

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.