1

I am playing around with some APIs in swift. I came across the Forecast.io API for weather, downloaded an objective-c wrapper, and created a bridging header in my xcode project. The only issue I am having is that I have a closure (objective-c block) that will not execute. Here is the code:

    var geocoder:CLGeocoder = CLGeocoder()
    geocoder.geocodeAddressString("1 Infinite Loop, Cupertino, CA", completionHandler: {objects, error in
        if (objects.count >= 0) {
            println("yes")
            curLocPlacemark = objects[0] as? CLPlacemark
            if(curLocPlacemark != nil) {
                curLocation = curLocPlacemark!.location
            }
        } else {
            println("no")
        }
    })

When debugging, the debugger gets to the line geocoder.geocodeAddressString("1 Infinite Loop, Cupertino, CA", completionHandler: {objects, error in, and then skips over the rest of the lines showed. Is this just a dumb syntax error I can't find? Thanks!

mjfish93
  • 95
  • 8

1 Answers1

2

The code inside the closure is executed asynchronously -- it's wrapped up and executed by the geocoder upon completion of the address string geocoding. (That's what a closure is -- wrapped up code and context for later execution.) Are you seeing the correct output in your log?

Nate Cook
  • 92,417
  • 32
  • 217
  • 178
  • No, but this might be the problem. Right after this block of code I get an error for unwrapping `curLocation`, which I guess can be because the code that assigns a value to `curLocation` hasn't be run yet, but is about to be? How would I solve this? – mjfish93 Sep 17 '14 at 03:14
  • 1
    Getting `curLocation` is asynchronous, so you can't access it right away. You should move code that depends on `curLocation` into the closure or into a method you call from within the closure. – Nate Cook Sep 17 '14 at 03:23