Swift map、flatMap、compactMap、filer、reduce的使用总结

Swift 提供了map、flatMap、compactMap、filer、reduce这几个高阶函数支持。

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

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

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

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

2,flatMap与map的区别

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

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

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

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

    (2)flatMap还能把多维数组变成一维数组:

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

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

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

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

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

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

4、compactMap: 当后面的闭包中返回Optional的时候,在Swift 4.1中应该使用compactMap代替map。

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

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

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

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

6、reduce:计算,可以对数组的元素进行计算:

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

func appendString(string1: String, string2: String) -> String {
    return string1 == "" ? string2 : string1 + "、" + string2
}
// reduce方法中的第一个参数是初始值
stringArray.reduce("", appendString)

stringArray.reduce("", {(string1, string2) -> String in
    return string1 == "" ? string2 : string1 + "、" + string2
})

// $0表示计算后的结果, $1表示数组中的每一个元素
stringArray.reduce("", {
    return $0 == "" ? $1 : $0 + "、" + $1
})

你可能感兴趣的:(移动开发,项目问题)