1

Why do I get a EXC_BAD_INSTRUCTION with just an empty call to geocodeAddressString:

geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in 

} as! CLGeocodeCompletionHandler)
Rob
  • 415,655
  • 72
  • 787
  • 1,044
jimijon
  • 2,046
  • 1
  • 20
  • 39

1 Answers1

2

The issue in your case is that error is an Error? reference in Swift 3, no longer a NSError?. Thus your forced cast is failing. You can fix that like so:

geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [CLPlacemark]?, error: Error?) -> Void in

} as! CLGeocodeCompletionHandler)

But that as! CLGeocodeCompletionHandler is not needed. If it suggested that cast, it probably only did so because it noticed that your closure was not of the right type.

Frankly, even easier, just let it infer the right types and you don't have to worry about this sort of issue:

geocoder.geocodeAddressString(address) { placemarks, error in 

}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • I thought I had tried it with error also, but, anyway your second variant does work ... thanks. – jimijon Oct 17 '16 at 22:17
  • Make sure you're using [weak self] in that callback or you could crash. – Gargoyle Jan 07 '17 at 08:26
  • @Gargoyle - No, it won't crash if we don't do `[weak self]`. Using `[unowned self]` could easily crash, but not just omitting `[weak self]`. As to whether you use `[weak self]` or not is merely a question of whether you need to keep a strong reference to the object in question or not. If it's merely updating UI controls, then `[weak self]` is a good idea. But if you're doing other stuff, too (e.g. updating model or persistent storage), then keeping the strong reference might be more appropriate. It just depends upon what you're doing in that closure. – Rob Jan 07 '17 at 09:23
  • If you don't use weak you'll run into issues where the geocode starts and then the person navigates away from the view controller. If you capture a strong reference to self then you have a retain cycle as the VC has you and you have it. – Gargoyle Jan 07 '17 at 15:07
  • That is simply not true. It is simply a strong reference, but one that is resolved as soon as the geocode call finishes or times out. But it's not a cycle. Yes, there are times that you absolutely must use weak references in closures to avoid strong reference cycles (when the object has a strong reference to that closure, itself), but this is not one of those cases. – Rob Jan 07 '17 at 22:46