Swift throw from closure nested in a function

前端 未结 5 1472
醉话见心
醉话见心 2020-12-30 21:15

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 possibl

5条回答
  •  梦毁少年i
    2020-12-30 21:35

    Because throwing is synchronous, an async function that wants to throw must have an inner closure that throws, such as this:

    func insertEventToDefaultCalendar(event :EKEvent, completion: (() throws -> Void) -> Void) {
        let eventStore = EKEventStore()
        switch EKEventStore.authorizationStatusForEntityType(.Event) {
        case .Authorized:
            do {
                try insertEvent(eventStore, event: event)
                completion { /*Success*/ }
            } catch {
                completion { throw CalendarEventError.Failed }
            }
    
            case .Denied:
                completion { throw CalendarEventError.AccessDenied }
    
            case .NotDetermined:
                eventStore.requestAccessToEntityType(EKEntityType.Event, completion: { (granted, error) -> Void in
                    if granted {
                        let _ = try? self.insertEvent(eventStore, event: event)
                        completion { /*Success*/ }
                    } else {
                        completion { throw CalendarEventError.AccessDenied }
                    }
            })
            default:
                break
        }
    }
    

    Then, at the call site, you use it like this:

       insertEventToDefaultCalendar(EKEvent()) { response in
            do {
                try response()
                // Success
            }
            catch {
                // Error
                print(error)
            }
        }
    

提交回复
热议问题