【发布时间】:2021-04-01 06:25:40
【问题描述】:
我正在为 Hacker News 编写一个网络客户端。我正在使用他们的official API。
我无法修改我的网络客户端以使用结构而不是故事 cmets 的类。它适用于类,尤其是异步递归闭包。
这是我的数据模型。
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 不适用于异步闭包递归。它适用于类,因为类被引用而结构被复制,这会导致一些问题。
如何调整我的网络客户端以使用结构?有没有办法将我的方法重写为一个方法而不是两个?一种方法是针对顶级(根)cmets,而另一种方法是针对每个顶级(根)评论回复进行递归。
【问题讨论】:
标签: swift asynchronous recursion network-programming closures