kgreenek
kgreenek

Reputation: 5024

Swift2 closure that throws

I am trying to create a closure that can throw, and pass it as an argument to another function. For example:

extension NSManagedObjectContext {

  /// The same as performBlockAndWait, except it can handle closures that throw.
  func performBlockAndWaitOrThrow(block: (() -> throws Void)) throws {
    // ...
    try block()
  }
}

Note that the |block| argument is a closure that can throw.

However, this doesn't compile. Is there any way to do this?

Upvotes: 2

Views: 272

Answers (1)

rob mayoff
rob mayoff

Reputation: 385700

The throws keyword should come before the arrow. This compiles:

extension NSManagedObjectContext {

    /// The same as performBlockAndWait, except it can handle closures that throw.
    func performBlockAndWaitOrThrow(block: (() throws -> Void)) throws {
        // ...
        try block()
    }
}

Upvotes: 4

Related Questions