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)
}
我想将test1的闭包传递给test2,但是test2的闭包可能有多种类型,运行时出错,EXC_BAD_INSTRUCTION
这样做可以吗?
最佳答案
这是对泛型的误用。如果您不关心使用什么类型作为 completion
的参数,请将其参数键入 Any:
func test(user: String, completion: @escaping (Any) -> Void) {
completion(user)
}
关于Swift,如何传递多种类型的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39629789/