Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/103.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift回调语法问题_Ios_Swift - Fatal编程技术网

Ios Swift回调语法问题

Ios Swift回调语法问题,ios,swift,Ios,Swift,我是Swift新手,我试图声明一个接收回调的函数 func getAll(callback: (students: [Student]!) -> Void) { // http request to get a list of students and parse it callback(students: students) } 调用函数时,我正在执行以下操作: obj.getAll() { (students: [Student]!) in //

我是Swift新手,我试图声明一个接收回调的函数

func getAll(callback: (students: [Student]!) -> Void) {
    // http request to get a list of students and parse it

    callback(students: students)
}
调用函数时,我正在执行以下操作:

obj.getAll() {
    (students: [Student]!) in

    // Callback code
}
但是它不会构建,它说:
不能用类型为“([Student]!)->”的参数列表调用getAll


我在下面作为指导,我遗漏了什么?

您不向学生发送参数,而是接收一个参数,这就是为什么您要这样实现它:

struct Student {

}

func getAll(callback: (students: [Student]!) -> Void) {
    // http request to get a list of students and parse it
    let students = [Student]()

    callback(students: students)
}

getAll { (students) -> Void in
    println(students)
}
obj.getAll { (students) -> Void in
    // Callback code
}

如果您不确定闭包,请始终使用autocomplete,这样就不必担心语法问题。希望这有帮助。

删除通话中的类型声明

obj.getAll() {
    students in
    // Callback code
}

作为旁注。您应该能够省略
->Void
。斯威夫特含蓄地补充道,这和他拥有的有什么不同?不一样吗?没什么不同。但我解释了争论和学生之间的区别。我想我应该详细阐述一下我的答案,这样就可以更多地了解Swift闭包。仅仅给某人代码而不解释不会帮助某人成为一个更好的开发人员。虽然我同意没有必要在那里声明,但这并不是一个错误。我怀疑他是因为声明而出错的(因为声明是完全有效的:学生应该是[Student]类型!)。还是我在这里感到困惑?顺便说一句,我也不太明白其中的道理。您确实将函数作为参数发送,因此可以声明类型。