For example:
func f(x: Int) -> Int { return x } func h(f: @escaping (Int) -> Any) { if (f is (Int) -> Int) { print(f(1)) } else { print("invalid") } } h(f: f)
I expect it to print out 1
but it actually prints out invalid
.
For example:
func f(x: Int) -> Int { return x } func h(f: @escaping (Int) -> Any) { if (f is (Int) -> Int) { print(f(1)) } else { print("invalid") } } h(f: f)
I expect it to print out 1
but it actually prints out invalid
.
You can rewrite
h
into a generic function:But the better way to to write type-specific overloads for
h
and a generic catch-all for the rest (if you need it at all).There's a workaround using generics:
Using
Any
is almost always a sign of code smell, you should try to rely as much as possible of the type safety that Swift provides. You can achieve this by makingh
generic, thus verifiable at compile time.Heck, you could even give up the generic overload, thus you'll have for free compile checks instead of runtime failures (much, much reliable and predictive)