1
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?

0

2 Answers 2

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

1

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)
}

1 Comment

This is a good answer too. Very nice. If the OP's intention is that the user type should match the completion function's parameter type, then this is right (and my answer is not).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.