Ios 请帮助我理解这个代码片段

Ios 请帮助我理解这个代码片段,ios,swift,callback,completionhandler,Ios,Swift,Callback,Completionhandler,我对斯威夫特很陌生 fetchAllRooms函数接受另一个名为completion的函数,该函数接受参数数组remoterooms并返回void 现在,在结束时,将使用参数RemoteRoom调用完成块(语法类似于Objective c中的块回调)。RemoteRoom已初始化&完成块被称为完成(rooms)。但完成区块的主体在哪里?执行行:completion(rooms)时要执行哪些行 调用该函数时,块部分的完成被调用(执行)。调用completion(rooms)将执行已调用此函数的完成

我对斯威夫特很陌生

fetchAllRooms
函数接受另一个名为completion的函数,该函数接受参数数组remoterooms并返回void


现在,在结束时,将使用参数RemoteRoom调用完成块(语法类似于Objective c中的块回调)。RemoteRoom已初始化&完成块被称为
完成(rooms)
。但完成区块的主体在哪里?执行行:
completion(rooms)
时要执行哪些行

调用该函数时,块部分的
完成
被调用(执行)。调用
completion(rooms)
将执行已调用此函数的完成块
fetchAllRooms

public func fetchAllRooms(completion: ([RemoteRoom]?) -> Void) {
  let url = NSURL(string: "http://localhost:5984/rooms/_all_docs?include_docs=true")!

  let urlRequest = NSMutableURLRequest(
    URL: url,
    cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
    timeoutInterval: 10.0 * 1000)
  urlRequest.HTTPMethod = "GET"
  urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

  let task = urlSession.dataTaskWithRequest(urlRequest)
    { (data, response, error) -> Void in
    guard error == nil else {
      print("Error while fetching remote rooms: \(error)")
      completion(nil)
      return
    }

    guard let json = try? NSJSONSerialization.JSONObjectWithData(data!,
      options: []) as? [String: AnyObject] else {
        print("Nil data received from fetchAllRooms service")
        completion(nil)
        return
    }

    guard let rows = json["rows"] as? [[String: AnyObject]] {
      print("Malformed data received from fetchAllRooms service")
      completion(nil)
      return
    }

    var rooms = [RemoteRoom]()
    for roomDict in rows {
      rooms.append(RemoteRoom(jsonData: roomDict))
    }

    completion(rooms)
  }

  task.resume()
}

完成块的主体是传递的函数或闭包的主体。以下示例都执行相同的操作:

self.fetchAllRooms() { rooms in
    //When you call completion(rooms) this block will be executed and you get [RemoteRoom] 
    in rooms instance

    //do something with rooms instance here
} 

Objective-C块和Swift闭包是同一件事,名称不同,语法略有不同,但它们可以互换

在Objective-C中,系统有一个UIView动画类方法
animateWithDuration:animations:
。想象一下它的实现:

func fetch(completion: (Int) -> Int) {
    print("executing fetch")

    let result = completion(5)
    print("completion(5) returns \(result)")
}

// calling it passing a function with the right signature
func addOne(i: Int) -> Int {
    return i + 1
}

fetch(completion: addOne)

// passing a closure
fetch(completion: { i in return i + 1 })

// same with trailing closure syntax
fetch() { i in
    return i + 1
}

// () isn't needed if completion is the only parameter
fetch { i in
    return i + 1
}

// simplified closure removing parameter name and return
fetch { $0 + 1 }
动画块的主体在哪里

这是来电者提供的。行
animations()
调用传入方法的块

fetch()
函数也是如此。它需要一个名为
completion
的块/闭包。fetch函数使用异步URLSession(Objective-C中的NSURLSession)dataTask下载数据,并为数据任务提供完成处理程序

数据任务完成后,数据任务的完成处理程序代码将运行。在该完成处理程序中,
fetch()
函数调用传递给它的完成处理程序函数。(这里有两个级别的完成处理程序。)这是在Objective-C和Swift中使用aysnc库的一种非常常见的模式


Swift有一个“尾随闭包”语法,就像Objective-C一样。在两种语言中,如果函数的最后一个参数是块/闭包,则可以将块闭包拉到括号外,跳过参数标签,只需为块/闭包提供大括号。在Objective-C中,您必须在块前面加上可怕的
^
,以使编译器满意,但在其他方面,这两者非常相似。

感谢Nirav的回答。当调用块时,我可以理解,但是块体在哪里?(虽然我不太确定闭包是否与块的工作方式相同)@user804417在您调用
fetchAllRooms
函数时,
completion(rooms)
的术语主体是
{rooms in}
。收到了,非常感谢。我还有一个问题,@user804417,它是什么?{(数据、响应、错误)->Void in,这个in关键字在这里是做什么的?谢谢你的全面回答@vacawwama。我有两个问题。如果我比较“//传递闭包”&“//与尾随闭包语法相同”何时使用闭包,何时使用尾随闭包?任何具体情况?为什么这in关键字用于?输入参数?为什么这$0用于?如果in用于描述输入参数,那么问题行“{(数据、响应、错误)->Void in”中的情况如何@user804417,如果最后一个参数采用闭包,则通常使用尾随闭包语法。关键字中的
将参数与闭包正文分开。
$0
表示第一个参数。如果有3个参数,则使用
$0
$1
$2
。非常感谢,先生!这是crystal clear now!let task=urlSession.dataTaskWithRequest(urlRequest){(数据,响应,错误)->Void in guard error==nil else{print(“获取远程房间时出错:(错误)”)completion(nil)return}下面的块是否可以替代上面的块?let task=urlSession.dataTaskWithRequest(urlRequest){(数据、响应、错误)->if-let-myerror=error中的Void!{print(“获取远程房间时出错:(myerror)”)完成(nil)返回}
@interface UIView

+(void) animateWithDuration: (int) duration, animations: (void (^)(void)) animations {
   //set up animation
   animations();
   //finish animations
}