Reputation: 157
func test1(user: String, completion: @escaping (TestModel) -> Void) {
test2(user: "test", completion: completion as! (Any) -> Void //failed here)
}
func test2(user: String, completion: @escaping (Any) -> Void) {
completion(user)
}
I want to pass test1's closure to test2, but test2's closure may have multiple type, it get error when run, EXC_BAD_INSTRUCTION
Is it passable to do this?
Upvotes: 1
Views: 991
Reputation: 24341
completion
in the above method must take an argument of type T
. So anything that you use as an argument to completion
must also be of type T
. So user
must be of type T
, i.e.
func test<T>(user: T, completion: @escaping (T) -> Void)
{
completion(user)
}
Upvotes: 1
Reputation: 535306
This is a misuse of a generic. If you don't care what type is used as the argument to completion
, type its parameter as Any:
func test(user: String, completion: @escaping (Any) -> Void) {
completion(user)
}
Upvotes: 1