每次在这里提问,都是因为不知道要搜索什么,对此我感到非常抱歉。
无论如何,我正在尝试使用 Google Maps SDK 创建一个应用程序,并且我遵循了 Ray Wenderlich 网站上 Ron Kliffer 的一个非常好的教程。但是,我想对其进行大量自定义,因此我尝试阅读每一行并了解它的作用。现在我遇到了一个 block ,我不明白其中的语法。
func fetchPlacesNearCoordinate(coordinate: CLLocationCoordinate2D, radius:
Double, types:[String], completion: (([GooglePlace]) -> Void)) -> ()
这就是被调用的函数,这样:
dataProvider.fetchPlacesNearCoordinate(coordinate, radius:mapRadius, types: searchedTypes) { places in
for place: GooglePlace in places {
我根本不明白 completion: 位和“places in”位。接下来是,如果我没记错的话,一个“foreach”的东西(或者在 Swift 语法中的 for in。
编辑:重新格式化
Edit2:是的,在函数体中创建了一个 GooglePlaces 数组,并且在 forin-thing 中使用了相同的数组(我猜)。
请您参考如下方法:
{ places in
for place: GooglePlace in places {
// ...
}
}
是一个闭包。将军closure expression syntax是
{ (param_1 : type_1, ..., param_n : type_n ) -> return_type in
statements
}
当闭包类型已知或可以从上下文中推断出时,您可以省略参数类型、返回类型(以及参数周围的括号):
{ param_1, ..., param_n in
statements
}
所以第一个 places 是(唯一的)闭包参数,它是 在 for-in 语句中使用。
请注意,由于闭包的类型为 ([GooglePlace]) -> Void, places 参数的类型为 [GooglePlace] 并且 for-in 循环中的显式类型注释不是必需的:
{ places in
for place in places {
// ...
}
}
