LearnSwift-小白学习map,reduce方法

数组的map、reduce方法

map方法将遍历序列中每个元素

[1,2,3,4,5,6].map { (i) -> Int in
    return i * 2
}

简化版

[1,2,3,4,5,6].map({$0 * 2})

reduce: i 这里是一个累加器(并不表示相加),保存了前一次运算的结果。

[1,2,3,4,5,6].reduce(1) { (i, element) -> Int in
    print(i,element)
    return i * element
}

上面的reduce方法可以简化为

[1,2,3,4,5,6].reduce(1, combine: *)

下面来看看flatMap,该函数会忽略为nil的集合元素。

let persons: [[String: AnyObject]] = [["name": "Carl Saxon", "city": "New York, NY", "age": 44],
                                      ["name": "Travis Downing", "city": "El Segundo, CA", "age": 34],
                                      ["name": "Liz Parker", "city": "San Francisco, CA", "age": 32],
                                      ["name": "John Newden", "city": "New Jersey, NY", "age": 21],
                                      ["name": "Hector Simons", "city": "San Diego, CA", "age": 37],
                                      ["name": "Brian Neo", "age": 27]] //注意这家伙没有 city 键值
//找到住在CA的居民。
func peopleFromState(state:String,persons:[[String:AnyObject]]) -> Int{

    return persons.flatMap { $0["city"]?.componentsSeparatedByString(", ").last}.filter { $0 == state}.count
}
peopleFromState("CA", persons: persons)

用reduce实现map、flatMap

func rmap(element:[Int],transform:(Int)->Int ) ->[Int]{
    return element.reduce([Int](), combine: { (var accemulator:[Int], obj:Int) -> [Int] in
        print(accemulator,obj)
        accemulator.append(transform(obj))
        return accemulator
    })
}

rmap([1,2,3,4,5,6], transform: {$0 * 2})
func rmap2(element:[Int],transform:(Int)->Int) -> [Int] {
    return element.reduce([Int](), combine: {$0  + [transform($1)]})
}
let array = rmap2([1,2,3,4,5,6], transform: {$0 * 2})
print(array)

结果都是[2, 4, 6, 8, 10, 12]

理解 $0, $1
$0,$1是一个常量,类型根据所在函数的参数类型决定。

LearnSwift-小白学习map,reduce方法_第1张图片
¥0类型.png
LearnSwift-小白学习map,reduce方法_第2张图片
$1类型.png

为何它们是这个类型呢?
其所在函数是combine,那么$0和$1的类型都是由combine这个(函数/闭包/方法)的第二个参数类型决定的。所以我们来看看reduce函数的定义:

public func reduce(initial: T, @noescape combine: (T, Self.Generator.Element) throws -> T) rethrows

$0代表第一个参数,其类型这里是[Int],$1代表的是combine内的第二个参数,所以其类型就是Int的。

用reduce实现filter

func rfilter(element:[Int],filter:(Int)->Bool)-> [Int]{

    return element.reduce([Int](), combine: { (var acc:[Int], value:Int) -> [Int] in
        if filter(value){
            acc.append(value)
        }

        return acc
    })
}

let xxc = rfilter([1,2,3,4,5,6], filter: { $0 > 3})
print(xxc)


func rfilter2(element:[Int],filter:(Int)->Bool)-> [Int]{

    return element.reduce([Int](), combine: { guard filter($1) else{ return $0}
        return $0 + [$1]
    })
}

let oos = rfilter2([1,2,3,4,5,6], filter: {$0 > 3 })
print(oos)

再看前面提过的问题:找到住在CA的居民。并且计算他们的平均年龄

func peopleFromState(state:String,persons:[[String:AnyObject]]) -> (population:Int,averageAge:CGFloat){

    //return persons.flatMap { $0["city"]?.componentsSeparatedByString(", ").last}.filter { $0 == state}.count

    typealias Result = (population:Int,averageAge:CGFloat)

    let u = persons.reduce((populatoin:0,averageAge:0.0)) { (var result:Result, dic:[String:AnyObject]) -> Result in

        guard let locationStr = dic["city"]?.componentsSeparatedByString(", ").last,let personAge = dic["age"] where locationStr == state else{ return result}

        return (result.population + 1,result.averageAge + CGFloat(personAge as! NSNumber))
    }

    return (u.populatoin,u.averageAge / CGFloat(u.populatoin))
}
let result = peopleFromState("CA", persons: persons)
result.population // 3
result.averageAge // 34.333333334

你可能感兴趣的:(LearnSwift-小白学习map,reduce方法)