Swift:减少闭包
Swift: Reduce with closure
代码:
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
数组上的reduce函数,在闭包中传递了两个参数:(mapRect: MKMapRect, treasure: Treasure)
。闭包如何知道第二个参数将是 treasures
数组中的元素,而第一个参数将是这个闭包 returns 的结果?
默认情况下,闭包中传递的第二个参数将是执行 reduce 函数的数组中的元素吗?
如果你看一下reduce的定义:
func reduce<S : SequenceType, U>(sequence: S, initial: U, combine: @noescape (U, S.Generator.Element) -> U) -> U
闭包的第一个参数是结果,第二个是序列的元素。
Swift 的数组 class 有一个 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
的定义决定了参数传递给你提供的闭包的顺序。
注意 Swift 的 reduce
的实际定义比我上面提供的更复杂,但上面的例子是基本要点。
代码:
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
数组上的reduce函数,在闭包中传递了两个参数:(mapRect: MKMapRect, treasure: Treasure)
。闭包如何知道第二个参数将是 treasures
数组中的元素,而第一个参数将是这个闭包 returns 的结果?
默认情况下,闭包中传递的第二个参数将是执行 reduce 函数的数组中的元素吗?
如果你看一下reduce的定义:
func reduce<S : SequenceType, U>(sequence: S, initial: U, combine: @noescape (U, S.Generator.Element) -> U) -> U
闭包的第一个参数是结果,第二个是序列的元素。
Swift 的数组 class 有一个 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
的定义决定了参数传递给你提供的闭包的顺序。
注意 Swift 的 reduce
的实际定义比我上面提供的更复杂,但上面的例子是基本要点。