hgwhittle
hgwhittle

Reputation: 9426

Can't call function with Swift Closure as argument

I've written a function to make a web service call, get some JSON, form an array with the data, and return it in a closure on completion. I'm new with this syntax, but the compiler says it's right so I'm assuming it is.

class APIHelper: NSObject {

    func getArticles(completion: (result: NSArray, error: NSError)->()) {

    }
}

My problem is, I can't figure out how to call this method. When I try to, the autocomplete doesn't show my completion closure. Instead it acts like I'm supposed to pass that method an instance of the class it's declared in (APIHelper).

//View Controller
override func viewDidLoad() {
    super.viewDidLoad()

    APIHelper.getArticles( { (result: Array!, error: NSError!) -> Void in

    })  //COMPILER ERROR: '(NSArray!, NSError!) -> Void' is not convertible to 'APIHelper'
}

Has anyone else gotten this error before? If so, how can I call this method and implement the closure?

Upvotes: 2

Views: 2966

Answers (2)

Mick MacCallum
Mick MacCallum

Reputation: 130183

First and foremost, it looks like you're trying to call an instance method of APIHelper on the class itself. If you wish to do this, you either need to make an instance of the class to be the receiver of the method, or you need to declare your method as a class method to be able to use it in the way that you're trying.

class APIHelper: NSObject {

    class func getArticles(completion: (result: NSArray, error: NSError)->()) {

    }
}

Additionally, the types of your parameters must be the same as those used as arguments. If you've declared the method to take an NSArray object, you should access it as NSArray, not Array, so you should be calling the method like this.

APIHelper.getArticles( { (result: NSArray, error: NSError) -> Void in
    // stuff            
})

Which can be simplified down to the following, which allows Swift's type inference to determine the types of the parameters so you don't have to worry about mismatching them.

APIHelper.getArticles { result, error in
    // stuff        
}

Upvotes: 5

Sean
Sean

Reputation: 370

The easiest way to call your function would be with a trailing closure, like this:

APIHelper.getArticles { (result:Array!, error:NSError!) -> Void in
    NSLog("No more error!")
}

Since your function has only one argument, and since that argument is a closure, you're able to do away with the parentheses for the function arguments.

Upvotes: 0

Related Questions