Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Lewis Edmonds
Lewis Edmonds
2,823 Points

Completion Handler in Swift

I've got a closure calculating distance and time between two points, but I need to extract the values outside of the closure.

I'm pretty sure a completion handler is the way to go, but not too sure how to implement it.

My code:

var completionHandlers: [() -> Void] = []

@IBAction func calculateItinerary(_ sender: Any) {


    for index in 0...coordsOfCollective.count - 2 { /

        let sourceLocation = MKPlacemark(coordinate: coordsOfCollective[index]) 

        let destinationLocation = MKPlacemark(coordinate: coordsOfCollective[index + 1])

        let sourceMapItem = MKMapItem(placemark: sourceLocation)
        let destinationMapItem = MKMapItem(placemark: destinationLocation)


        let request = MKDirectionsRequest()
        request.source = sourceMapItem
        request.destination = destinationMapItem

        request.transportType = .automobile
        request.requestsAlternateRoutes = false


        let directions = MKDirections(request: request)

        directions.calculate { response, error in
            if let route = response?.routes.first {
               print("Distance: \(route.distance/1000) km, ETA: \(route.expectedTravelTime/60) mins")

            self.distances.append(route.distance/1000)
            self.journeyTimes.append(route.expectedTravelTime/60)

                print(self.distances)
                print(self.journeyTimes)

                completionHandlers.append(?????)


            } else {
                print("Error!")
            }

        }
    }

print(completionHandlers)

}

The directions.calculate has a declaration of calculate(completionHandler: @escaping MKDirectionsHandler), so I can see it is an escaping closure. But I don't know how I extract distances and journeyTimes arrays.

I don't have an input names completionHandler, and distances and journeyTimes produce Doubles, which aren't accepted by the completionHandlers array...

Any help is appreciated. Thanks.