user1107173
user1107173

Reputation: 10764

Swift: Reduce with closure

Code:

     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)
    }

In the code above, we are running the reduce function on treasures array, two parameters are passed in the closure: (mapRect: MKMapRect, treasure: Treasure). How does the closure know to that the second parameter will be the element from the treasures array and the first parameter will be result of the what this closure returns?

Is this something by default that the second parameter passed in the closure will be the element from the array that's executing the reduce function?

Upvotes: 0

Views: 472

Answers (2)

mipadi
mipadi

Reputation: 410792

Swift's array class has a definition of reduce that most likely looks something like this:

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

That is to say, the definition of reduce dictates the order in which parameters are passed to the closure you provide.


Note that the actual definition of Swift's reduce is more complicated than the one I provided above, but the example above is the basic gist.

Upvotes: 2

MirekE
MirekE

Reputation: 11555

If you look at the definition of reduce:

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

The first parameter of the closure is the result and the second is element of your sequence.

Upvotes: 1

Related Questions