Map、FlatMap、Filter、Reduce等函数

1.map:可以对数组中的每一个元素做一次处理

var values = [1,3,5,7,9]
let results = values.map { (element) -> Int in
    return element * 2
}

// 计算字符串的长度
let stringArray = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]
func stringCount(string: String) -> Int {
    return string.count
}
stringArray.map(stringCount)

stringArray.map({string -> Int in
    return string.count
})

// $0代表数组中的每一个元素
stringArray.map{
    return $0.count
}

2.flatMap与map不同之处:

(1)flatMap返回后的数组中不存在nil,同时它会把Optional解包

let arrayMap = ["Apple", "Orange", "Puple", ""]

let arr1 = arrayMap.map { a -> Int? in
    let length = a.count
    guard length > 0 else { return nil }
    return length
}
arr1 // [{some 5}, {some 6}, {some 5}, nil]

let arr2 = arrayMap.compactMap { a-> Int? in
    let length = a.count
    guard length > 0 else { return nil}
    return length
}
arr2 // [5, 6, 5]

(2)flatMap还能把数组中存有数组的数组(二维数组、N维数组)一同打开变成一个新的数组

let arrayMap1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

let arrResult1 = arrayMap1.map{ $0 }
arrResult1 // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

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

(3)flatMap也能把两个不同的数组合并成一个数组,这个合并的数组元素个数是前面两个数组元素个数的乘积

let fruits = ["Apple", "Orange", "Puple"]
let counts = [2, 3, 5]

let arrayMap2 = counts.flatMap { count in
    fruits.map ({ fruit in
        return fruit + "  \(count)"
    })
}
arrayMap2 // ["Apple 2", "Orange 2", "Puple 2", "Apple 3", "Orange 3", "Puple 3", "Apple 5", "Orange 5", "Puple 5"]

3.filer:过滤,可以对数组中的元素按照某种规则进行一次过滤

// 筛选出字符串的长度小于10的字符串
let stringArray1 = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]
func stringCountLess10(string: String) -> Bool {
    return string.count < 10
}
stringArray1.filter(stringCountLess10)

stringArray1.filter({string -> Bool in
    return string.count < 10
})

// $0表示数组中的每一个元素
stringArray1.filter{
    return $0.count < 10
}

4.reduce:计算,可以对数组的元素进行计算

// 将数组中的每个字符串用‘、’拼接
let stringArray2 = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]
var resultStr:String = ""

func appendString(string1: String, string2: String) -> String {
    return string1 == "" ? string2 : string1 + "、" + string2
}
// reduce方法中的第一个参数是初始值
resultStr = stringArray2.reduce("", appendString)
resultStr
resultStr = stringArray2.reduce("", {(string1, string2) -> String in
    return string1 == "" ? string2 : string1 + "、" + string2
})
resultStr
// $0表示计算后的结果, $1表示数组中的每一个元素
stringArray2.reduce("", {
    return $0 == "" ? $1 : $0 + "、" + $1
})
resultStr

你可能感兴趣的:(Map、FlatMap、Filter、Reduce等函数)