occurrence-typing

How to check/predicate function type in Swift?

为君一笑 提交于 2019-12-05 21:46:08
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 . There's a workaround using generics: func intF(x: Int) -> Int { return x } func stringF(x: Int) -> String { return "\(x)" } func h<T>(f: (Int) -> T) { if (T.self == Int.self) { print(f(1)) } else { print("invalid") } } h(f: intF) // prints: 1 h(f: stringF) // prints: invalid Using Any is almost always a sign of code smell, you should try to rely as much as possible of the