PIXEL
DOCK

I like the smell of Swift in the morning…

How to pass an error pointer to a function in Swift

Posted: | Author: | Filed under: Swift | Tags: , | No Comments »

With the introduction of throwable in Swift 2 more and more functions implement the new error handling. However there are still some functions that expect you to pass an error pointer. This is especially the case when you are using an Objective-C framework in your Swift project.

So for an example let’s look at AFNetworking’s AFHTTPRequestSerializer’s method requestWithMethod:URLString:parameters:error:

If you are trying to implement it like you would in Objective-C you are in for a surprise:

var error: NSError
let request = AFHTTPRequestSerializer.serializer().requestWithMethod("GET", URLString: "https://yourDomain.com", parameters: nil, error: &error)

This will cause the following compiler error:

'&' used with non-inout argument of type 'NSErrorPointer' (aka 'AutoreleasingUnsafeMutablePointer>')

The fix for this is much more simple than the error message suggests. The thing is, that error can be nil if the method is successful. Because of that, error has to be an Optional:

var error: NSError?
let request = AFHTTPRequestSerializer.serializer().requestWithMethod("GET", URLString: "https://yourDomain.com", parameters: nil, error: &error)

This works fine now