Swift之高階函數map、flatMap、filter、reduce

Swift之高階函數map、flatMap、filter、reduce


 
Swift相比於Objective-C又一個重要的優點,它對函數式編程提供了很好的支持,Swift提供了map、filter、reduce這三個高階函數作爲對容器的支持。

map

解釋:可以對數組中的每一個元素做一次處理

var arrayList: [Int] = [90, 19, 9, 78, 10, 32, 45]
let mapList = arrayList.map { (number) -> String in
    return "\(number)"
}//將數字Int轉化爲字符串
print(mapList)//得到的是新函數
//結果:mapList:["90", "19", "9", "78", "10", "32", "45"]

官方文檔解釋:

/// Returns an array containing the results of mapping the given closure
    /// over the sequence's elements.
    ///
    /// In this example, `map` is used first to convert the names in the array
    /// to lowercase strings and then to count their characters.
    ///
    ///     let cast = ["Vivien", "Marlon", "Kim", "Karl"]
    ///     let lowercaseNames = cast.map { $0.lowercased() }
    ///     // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
    ///     let letterCounts = cast.map { $0.count }
    ///     // 'letterCounts' == [6, 6, 3, 4]
    ///
    /// - Parameter transform: A mapping closure. `transform` accepts an
    ///   element of this sequence as its parameter and returns a transformed
    ///   value of the same or of a different type.
    /// - Returns: An array containing the transformed elements of this//返回一個數組array
    ///   sequence.
    @inlinable public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
//T 是泛型,返回你需要的類型,可以知道官方demo中簡寫方式
let letterCounts = cast.map { $0.count }//各個長度

flatMap與map不同之處

注意:序列可選類型,Swift 4.1之前可以使用flatMap,現在需要compactMap
一般情況下mapflatMap的功能是相似的,都可以執行map工作。
compactMap的改變是在於將flatMap處理non-optional序列類型,compact處理optional類型

  1. flatMap返回後的數組中不存在nil,同時它會把Optional解包
let strList:[String?] = ["Apple", "Orange", "Puple", "", nil]
let lengthListOp = strList.map { (item) -> Int? in
    return item?.count
}

lengthListOp // [Optional(5), Optional(6), Optional(5), Optional(0), nil]
let lengthList = strList.compactMap { (item) -> Int? in
    guard item.count > 0 else {
        return nil
    }
    return item.count
}
lengthList // [5, 6, 5, 0]
  1. compactMap還能把數組中存有數組的數組(二維數組、N維數組)一同打開變成一個新的數組
let newList = [["2", "32", "Apple"], ["02", "132", "Orange"], ["20", "320", "Puple"]]
let mapNew = newList.map { (list) -> [String] in
   return list.map({ (item) -> String in
        return item
    })
}
//簡寫代碼:僅僅只是查看的話
let simpleNew = newList.map { $0}
print(mapNew)
print(simpleNew)
//結果:[["2", "32", "Apple"], ["02", "132", "Orange"], ["20", "320", "Puple"]]

let flatNew = newList.flatMap { $0}
print(flatNew)
//結果:["2", "32", "Apple", "02", "132", "Orange", "20", "320", "Puple"]

  1. flatMap也能把兩個不同的數組合併成一個數組,這個合併的數組元素個數是前面兩個數組元素個數的乘積
let fruits = ["Apple", "Orange", "Puple"]
let counts = [2, 3]

let array = counts.flatMap { count in
    fruits.map ({ fruit in
        return fruit + "  \(count)"
    })
}
print(array)
//結果:["Apple  2", "Orange  2", "Puple  2", "Apple  3", "Orange  3", "Puple  3"]

filer

說明:過濾,可以對數組中的元素按照某種規則進行一次過濾

let fruits = ["Apple", "Orange", "Puple"]
let filterList = fruits.filter { (item) -> Bool in
    return item.contains("p")//包含p
}
print(filterList)
//結果:["Apple", "Puple"]

reduce

說明:方法把數組元素組合計算爲一個值,並且會接受一個初始值,這個初始值得類型可能和數組元素類型不同。

//字符串拼接
let fruits = ["Apple", "Orange", "Puple"]
let fruitReduce = fruits.reduce("100") { (result, item) -> String in
    return result + "、" + item
}
print(fruitReduce)
//結果:100、Apple、Orange、Puple

//方式二:
func appendString(string1: String, string2: String) -> String {
    return  string1 + "、" + string2
}
let newFruitReduce = fruits.reduce("10", appendString)
//結果:10、Apple、Orange、Puple

有關Swift.map高階函數的應用

這些函數不僅僅使用與數組Array類型,一般凡是有序的數據例如:String子元素是ChartDictionary對應子元素一個鍵值對等等這些都是可以用這些高階函數,這些寶藏還需自己開發中挖掘
Demo如下:

let newStr = "Hello World".filter { (chart) -> Bool in
    return !chart.description.elementsEqual("o")
}
print(newStr)// 剔除掉字符串中的o
var dic: [String : Any] = ["name": "XiaoMing", "age": 12, "sex": "Man"]
let newDic = dic.mapValues { (item) -> String in
    return "\(item)"
}
print(newDic)

//結果如下:
Hell Wrld
["sex": "Man", "name": "XiaoMing", "age": "12"]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章