Kenta Labur
Kenta Labur

Reputation: 145

Swift: Passing in functions that throw exceptions

I have the following toy example

func identity<T>(a : T) -> T{
  return a
}

func applyIdentity<T>(f : T->T, t:T) -> T{
  return f(t)
}

applyIdentity(identity, t:1)

And this works without a hitch. However, once I try to throw an exception in identity like so:

enum MyError: ErrorType{
  case MyErrorFoo
};

func identity<T>(a : T) throws -> T{
  if (true) {
    return a
  } else {
    throw MyError.MyErrorFoo
  }
}
...

The type checker complains on the applyIdentity(identity, t:1) call with message:

Argument for generic parameter 'T' could not be inferred

Any idea why this may be happening?

Upvotes: 7

Views: 2771

Answers (1)

Martin R
Martin R

Reputation: 539805

Your (second) identity() method can throw an error, therefore it has the type T throws -> T, not T -> T.

If applyIdentity() should just forward an error thrown in f() to the caller then you can define it as

func applyIdentity<T>(f : T throws ->T , t:T) rethrows -> T {
    return try f(t)
}

See also "Declarations" in the Swift book:

Rethrowing Functions and Methods

A function or method can be declared with the rethrows keyword to indicate that it throws an error only if one of it’s function parameters throws an error. These functions and methods are known as rethrowing functions and rethrowing methods. Rethrowing functions and methods must have at least one throwing function parameter.

Upvotes: 10

Related Questions