简体   繁体   English

无法使用Swift Closure作为参数调用函数

[英]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. 我编写了一个函数来进行Web服务调用,获取一些JSON,与数据形成数组,并在完成时以闭包形式返回。 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). 相反,它的行为就像我应该将该方法传递给在(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? 如果是这样,如何调用此方法并实现闭包?

First and foremost, it looks like you're trying to call an instance method of APIHelper on the class itself. 首先,看起来您正在尝试在类本身上调用APIHelper的实例方法。 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. 如果已声明该方法采用NSArray对象,则应将其作为NSArray而不是Array进行访问,因此应像这样调用该方法。

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. 可以简化为以下内容,这使Swift的类型推断可以确定参数的类型,因此您不必担心参数不匹配。

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

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. 由于您的函数只有一个参数,并且该参数是一个闭包,因此您可以消除函数参数的括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM