【发布时间】:2018-12-26 09:43:38
【问题描述】:
我正在为 CoreData 实现一个辅助方法
public func doInMain(_ block: (NSManagedObjectContext) -> Void) {
guard let context = mainQueueContext else { return }
context.performAndWait({
block(context)
})
}
效果很好,可以这样调用:
CoreDataManager().doInMain { moc in
// do your fetch request with managed object context
}
但是当我想尝试doInMain块中的错误时,这很烦人,因为它不能被调用函数重新抛出。既然bloc是nonescaping,那就应该做。
所以我补充说:
public func doInMain(_ block: (NSManagedObjectContext) throws -> Void) rethrows {
guard let context = mainQueueContext else { return }
context.performAndWait({
try block(context)
})
}
但是 NSManagedObjectContext.performAndWait 不会重新抛出错误,所以它不会编译。
它试过这个:
public func doInMain(_ block: (NSManagedObjectContext) throws -> Void) rethrows {
guard let context = mainQueueContext else { return }
var thrownError: Error?
context.performAndWait({
do { try block(context) }
catch { thrownError = error }
})
if let error = thrownError {
throw error
}
}
但是现在编译器说A function declared 'rethrows' may only throw if its parameter does
我搞砸了吗?有解决办法吗?
谢谢
【问题讨论】:
-
我觉得你搞砸了 :) 为什么不改成
public func doInMain(_ block: @escaping (NSManagedObjectContext?, Error?) -> Void) { guard let context = mainQueueContext else { return } context.performAndWait({ block(context, nil) }) } -
因为我不希望我的方法是
@esccaping!performAndWait不是,所以我的方法应该被编译器认为是同步的。它确实简化了使用它
标签: swift error-handling try-catch throw