【发布时间】:2020-05-15 20:08:13
【问题描述】:
让我陷入 Swift 中的一件事是我的程序中completionBlocks 的永无止境的链;我不知道如何让 Swift 说 “好的,完成块现在完成了 - 回到主程序。”
在我的项目中,我正在编写一个简单的棋盘/纸牌游戏,它从一个非常小的 plist 加载其数据。
我编写了一个相当简单的 Plist 加载器,它加载 plist 并通过完成块返回 Data。它不做任何解析;它不关心你想如何解析它,它只是返回NSData (Data) 或错误。
我有一个Parser,它会触发 Plist 加载程序,获取 Data,然后使用新的 Swift Codable 协议对其进行解析。
// A static function to try and find the plist file on bundle, load it and pass back data
static func loadBoard(completionHandler: @escaping (Board?, Error?) -> Void) {
PListFileLoader.getDataFrom(filename: "data.plist") { (data, error) in
if (error != nil) {
print ("errors found")
completionHandler(nil, error)
}
else {
guard let hasData = data else {
print ("no data found")
completionHandler(nil, error)
return
}
do {
print ("found board")
let board = try decodeBoard(from: hasData) // Call a function that will use the decoder protocol
completionHandler(board, nil)
} catch {
print ("some other board error occured")
completionHandler(nil, error)
}
}
}
}
然后将解析后的数据返回给主程序,或者任何调用它的东西——例如; XCTest
我的 XCTest:
func testBoardDidLoad() -> Board? { // The return bit will show an error; but its fine without the return part
BoardParsePlist.loadBoard { (board, error) in
XCTAssertNotNil(board, "Board is nil")
XCTAssertNotNil(error, error.debugDescription)
// How do I now escape this and return flow to the normal application?
// Can I wrap this in a try-catch?
}
}
从分层视图来看,它有点像这样。
XCTest
... Calls the parser (completionBlock ...)
.... Parser calls the PListLoader (completionHandler: ...)
现在感觉我被困在应用程序的其余部分中
BoardParsePlist.loadBoard { (board, error) in
// ... rest of the app now lives here?
})
看来我正处于completionBlocks 的永无止境的循环中。
你如何“逃脱”或突破完成块并将流程返回到主应用程序?
我不确定我的解释是否正确,但希望能提供任何帮助。
感谢您的宝贵时间。
【问题讨论】: