结构的异步闭包递归



我正在为Hacker News编写一个网络客户端。我正在使用他们的官方API。

我在修改我的网络客户端以使用structs而不是用于故事评论的类时遇到了问题。它可以很好地处理类,尤其是使用异步递归闭包。

这是我的数据模型。

class Comment: Item {
var replies: [Comment?]?
let id: Int
let isDeleted: Bool?
let parent: Int
let repliesIDs: [Int]?
let text: String?
let time: Date
let type: ItemType
let username: String?
enum CodingKeys: String, CodingKey {
case isDeleted = "deleted"
case id
case parent
case repliesIDs = "kids"
case text
case time
case type
case username = "by"
}
}

这是我的网络客户端的一个示例。

class NetworkClient {
// ...
// Top Level Comments
func fetchComments(for story: Story, completionHandler: @escaping ([Comment]) -> Void) {
var comments = [Comment?](repeating: nil, count: story.comments!.count)

for (commentIndex, topLevelCommentID) in story.comments!.enumerated() {
let topLevelCommentURL = URL(string: "https://hacker-news.firebaseio.com/v0/item/(topLevelCommentID).json")!

dispatchGroup.enter()

URLSession.shared.dataTask(with: topLevelCommentURL) { (data, urlResponse, error) in
guard let data = data else {
print("Invalid top level comment data.")
return
}

do {
let comment = try self.jsonDecoder.decode(Comment.self, from: data)
comments[commentIndex] = comment

if comment.repliesIDs != nil {
self.fetchReplies(for: comment) { replies in
comment.replies = replies
}
}

self.dispatchGroup.leave()
} catch {
print("There was a problem decoding top level comment JSON.")
print(error)
print(error.localizedDescription)
}
}.resume()
}

dispatchGroup.notify(queue: .global(qos: .userInitiated)) {
completionHandler(comments.compactMap { $0 })
}
}

// Recursive method
private func fetchReplies(for comment: Comment, completionHandler: @escaping ([Comment?]) -> Void) {
var replies = [Comment?](repeating: nil, count: comment.repliesIDs!.count)

for (replyIndex, replyID) in comment.repliesIDs!.enumerated() {
let replyURL = URL(string: "https://hacker-news.firebaseio.com/v0/item/(replyID).json")!

dispatchGroup.enter()

URLSession.shared.dataTask(with: replyURL) { (data, _, _) in
guard let data = data else { return }

do {
let reply = try self.jsonDecoder.decode(Comment.self, from: data)
replies[replyIndex] = reply

if reply.repliesIDs != nil {
self.fetchReplies(for: reply) { replies in
reply.replies = replies
}
}

self.dispatchGroup.leave()
} catch {
print(error)
}
}.resume()
}

dispatchGroup.notify(queue: .global(qos: .userInitiated)) {
completionHandler(replies)
}
}
}

您可以像这样调用网络客户端来获取特定故事的评论树。

var comments = [Comment]()
let networkClient = NetworkClient()
networkClient.fetchStories(from: selectedStory) { commentTree in
// ...
comments = commentTree
// ...
}

将Comment类数据模型切换为struct不能很好地使用异步闭包递归。它适用于类,因为类是被引用的,而结构是被复制的,这会导致一些问题。

如何调整我的网络客户端以使用structs?有没有办法把我的方法重写成一个方法,而不是两个?一种方法是针对顶级(根(注释,而另一种方法则是针对每个顶级(根号(注释回复的递归。

考虑这个代码块

let reply = try self.jsonDecoder.decode(Comment.self, from: data)
replies[replyIndex] = reply
if reply.repliesIDs != nil {
self.fetchReplies(for: reply) { replies in
reply.replies = replies
}
}

如果Comment是一个结构,这将获取reply,并将其副本添加到replies数组中,然后在fetchReplies中更改原始reply(必须将其从let更改为var才能编译此行(,而不是数组中的副本。

因此,您可能希望在fetchReplies闭包中引用replies[replyIndex],例如:

let reply = try self.jsonDecoder.decode(Comment.self, from: data)
replies[replyIndex] = reply
if reply.repliesIDs != nil {
self.fetchReplies(for: reply) { replies in
replies[replyIndex].replies = replies
}
}

顺便说一下,

  • 调度组不能是属性,而必须是本地var(尤其是当您似乎在递归调用此方法时!(
  • 你有几个执行路径,你不会离开组(如果datanil,如果reply.repliesIDsnil,或者如果JSON解析失败(;以及
  • 您有提前离开组的执行路径(如果reply.repliesIDs不是nil,则必须将leave()调用移动到该完成处理程序闭包中(

我还没有测试过,但我建议这样做:

private func fetchReplies(for comment: Comment, completionHandler: @escaping ([Comment?]) -> Void) {
var replies = [Comment?](repeating: nil, count: comment.repliesIDs!.count)
let group = DispatchGroup() // local var

for (replyIndex, replyID) in comment.repliesIDs!.enumerated() {
let replyURL = URL(string: "https://hacker-news.firebaseio.com/v0/item/(replyID).json")!

group.enter()

URLSession.shared.dataTask(with: replyURL) { data, _, _ in
guard let data = data else { 
group.leave() // leave on failure, too
return
}

do {
let reply = try self.jsonDecoder.decode(Comment.self, from: data)
replies[replyIndex] = reply

if reply.repliesIDs != nil {
self.fetchReplies(for: reply) { replies in
replies[replyIndex].replies = replies
group.leave() // if reply.replieIDs was not nil, we must not `leave` until this is done
}
} else {
group.leave() // leave if reply.repliesIDs was nil
}
} catch {
group.leave() // leave on failure, too
print(error)
}
}.resume()
}

dispatchGroup.notify(queue: .main) { // do this on main to avoid synchronization headaches
completionHandler(replies)
}
}

最新更新