问题描述
我有一个抛出错误的函数,在这个函数中我在闭包内有一个,我需要从它的完成处理程序中抛出错误。这可能吗?
I have a function that throws an error, in this function I have a inside a
closure that I need to throw the error from it's completion handler. Is that possible ?
这是我到目前为止的代码。
Here is my code so far.
enum CalendarEventError: ErrorType {
case UnAuthorized
case AccessDenied
case Failed
}
func insertEventToDefaultCalendar(event :EKEvent) throws {
let eventStore = EKEventStore()
switch EKEventStore.authorizationStatusForEntityType(.Event) {
case .Authorized:
do {
try insertEvent(eventStore, event: event)
} catch {
throw CalendarEventError.Failed
}
case .Denied:
throw CalendarEventError.AccessDenied
case .NotDetermined:
eventStore.requestAccessToEntityType(EKEntityType.Event, completion: { (granted, error) -> Void in
if granted {
//insertEvent(eventStore)
} else {
//throw CalendarEventError.AccessDenied
}
})
default:
}
}
推荐答案
定义抛出的闭包时:
enum MyError: ErrorType {
case Failed
}
let closure = {
throw MyError.Failed
}
然后这个闭包的类型是()throws - > ()
以及将此闭包作为参数的函数必须具有相同的参数类型:
then type of this closure is () throws -> ()
and function that takes this closure as parameter must have the same parameter type:
func myFunction(completion: () throws -> ()) {
}
此功能你可以调用完成
关闭同步:
It this function you can call completion
closure synchronous:
func myFunction(completion: () throws -> ()) throws {
completion()
}
并且您必须使用尝试将
: throws
关键字添加到函数签名或调用完成!
and you have to add throws
keyword to function signature or call completion with try!
:
func myFunction(completion: () throws -> ()) {
try! completion()
}
或异步:
func myFunction(completion: () throws -> ()) {
dispatch_async(dispatch_get_main_queue(), { try! completion() })
}
在上一种情况下,您将无法捕获错误。
In last case you will not be able to catch error.
因此,如果完成
在 eventStore.requestAccessToEntityType
方法中关闭并且方法本身没有在其签名中抛出
或者如果完成
被异步调用那么你就不能抛出
来自这个闭包。
So if completion
closure in eventStore.requestAccessToEntityType
method and the method itself does not have throws
in its signature or if completion
is called asynchronously then you can not throw
from this closure.
我建议你将函数的以下实现传递给回调而不是抛出它:
I suggest you the following implementation of your function that passes error to callback instead of throwing it:
func insertEventToDefaultCalendar(event: EKEvent, completion: CalendarEventError? -> ()) {
let eventStore = EKEventStore()
switch EKEventStore.authorizationStatusForEntityType(.Event) {
case .Authorized:
do {
try insertEvent(eventStore, event: event)
} catch {
completion(CalendarEventError.Failed)
}
case .Denied:
completion(CalendarEventError.AccessDenied)
case .NotDetermined:
eventStore.requestAccessToEntityType(EKEntityType.Event, completion: { (granted, error) -> Void in
if granted {
//insertEvent(eventStore)
} else {
completion(CalendarEventError.AccessDenied)
}
})
default:
}
}
这篇关于从嵌套在函数中的闭包中快速抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!