把我扔进Swift的其中一件事是我的程序中的永无止境的completionBlocks
链;我不知道如何让Swift说:“好了,完成块现在完成了--回到主程序。”
在我的项目中,我正在编写一个简单的棋盘/纸牌游戏,它从一个非常小的plist加载它的数据。
我编写了一个相当简单的Plist加载器,它加载plist并通过一个Data
返回completionBlock。它不进行任何解析;它不关心如何解析它,它只是返回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?
})
我似乎处在completionBlock
的一个永无止境的循环中。
您如何“逃离”或突破完成块,并返回回主流应用程序?
我不确定我是否正确地解释了它,但希望能在这方面提供任何帮助。
谢谢您抽时间见我。
发布于 2020-05-15 20:19:47
不知道如何让Swift说“好的,完成块现在完成了--回到主程序”
。
没有办法,也没有必要说-这是自动发生的。
static func loadBoard(completionHandler: @escaping (Board?, Error?) -> Void) {
PListFileLoader.getDataFrom(filename: "data.plist") { (data, error) in
// completion handler code here
}
// "back to main"
}
在您的示例中,执行将以两种方式之一“返回主”,这取决于PListFileLoader.getDataFrom
是否异步运行。
如果它同步运行,则执行顺序为:
应用程序调用的loadBoard
getDataFrom
OTOH,如果getDataFrom
是异步的(例如,因为它执行网络请求),则顺序为:
您的应用程序调用loadBoard
getDataFrom
getDataFrom
启动的工作完成,它调用完成处理程序parameter
F 235
不管是哪种方式,你都不用特别努力就能回到main。
https://stackoverflow.com/questions/61827529
复制相似问题