【发布时间】:2019-03-07 15:14:21
【问题描述】:
我正在尝试重构我的代码,并希望在 closure 中返回 Bool。当我尝试时,它说它未使用并且不起作用。我可以用另一种方式来做,但我在重复我不想做的代码。我该怎么办。
func tableView(_ pTableView: UITableView, canEditRowAt pIndexPath: IndexPath) -> Bool {
// These lines are the one that work but would like to get rid of them
if let rowConversation = self.objectAtIndexPath(pIndexPath) as? Conversation {
if rowConversation.isGroupChat && rowConversation.expired {
return true
}
}
self.getRowConversation(pIndexPath: pIndexPath) {
// how to return true here
}
return false
}
private func getRowConversation(pIndexPath: IndexPath, completion pCompletion: () -> Void) {
if let rowConversation = self.objectAtIndexPath(pIndexPath) as? Conversation {
if rowConversation.isGroupChat && rowConversation.expired {
ConversationManager.shared.deleteConversationID(rowConversation.conversationID)
pCompletion()
}
}
}
【问题讨论】:
-
您不会以异步方式运行
getRowConversation,因此该函数中不需要pCompletion。只需让它返回 true/false 即可。如果您的问题是“我怎样才能异步运行getRowConversation并且仍然从tableView()返回真/假”,那么答案是:你不能。为了使用结果值,您需要等待函数完成。 -
什么是
objectAtIndexPath,它返回一个可选值?Conversation还有其他类型吗?代码看起来很麻烦。
标签: ios swift closures completionhandler