2015-05-31 69 views
0

代码:夫特:减少与闭合

 var treasures: [Treasure] = [] 
    treasures = [treasureA, treasureB, treasureC, treasureD, treasureE] 

    let rectToDisplay = self.treasures.reduce(MKMapRectNull) { 
     (mapRect: MKMapRect, treasure: Treasure) -> MKMapRect in 
     // 2 
     let treasurePointRect = MKMapRect(origin: treasure.location.mapPoint, size: MKMapSize(width: 0, height: 0)) 
     // 3 
     return MKMapRectUnion(mapRect, treasurePointRect) 
    } 

在上面的代码中,我们所运行的减少对treasures阵列的功能,两个参数被传递在闭合:(mapRect: MKMapRect, treasure: Treasure)。闭包如何知道第二个参数是来自treasures数组的元素,第一个参数是闭包返回的结果?

这是默认情况下,在闭包中传递的第二个参数将是数组中执行reduce函数的元素吗?

回答

2

斯威夫特的数组类有reduce的定义,最有可能看起来是这样的:

func reduce<T>(initial: T, fn: (T, T) -> T) -> T { 
    var val = initial 
    for e in self { 
     val = fn(val, e) 
    } 
    return e 
} 

也就是说,的reduce的定义决定了其参数传递给你提供的封闭顺序。


需要注意的是斯威夫特的reduce的实际定义比我上面提供的一个更复杂,但上面的例子是最基本的要点。

1

如果你看一下减少的定义:

func reduce<S : SequenceType, U>(sequence: S, initial: U, combine: @noescape (U, S.Generator.Element) -> U) -> U

关闭的第一个参数是结果,第二个是你的序列的元素。