gpt4 book ai didi

ios - Swift 从嵌套在函数中的闭包中抛出

转载 作者:IT王子 更新时间:2023-10-29 08:08:56 25 4
gpt4 key购买 nike

我有一个抛出错误的函数,在这个函数中,我有一个 inside a 闭包,我需要从它的完成处理程序中抛出错误。这可能吗?

到目前为止,这是我的代码。

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 -> () 并且以这个闭包为参数的函数必须有相同的参数类型:

func myFunction(completion: () throws -> ()) {
}

这个函数你可以同步调用completion闭包:

func myFunction(completion: () throws -> ()) throws {
completion()
}

并且您必须将 throws 关键字添加到函数签名或使用 try! 完成调用:

func myFunction(completion: () throws -> ()) {
try! completion()
}

或异步:

func myFunction(completion: () throws -> ()) {
dispatch_async(dispatch_get_main_queue(), { try! completion() })
}

在最后一种情况下,您将无法捕获错误。

因此,如果 eventStore.requestAccessToEntityType 方法中的 completion 闭包,并且该方法本身的签名中没有 throws 或者如果 completion 被异步调用,那么你不能从这个闭包中throw

我建议您将错误传递给回调而不是抛出错误的函数的以下实现:

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:
}
}

关于ios - Swift 从嵌套在函数中的闭包中抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33213715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com