[英]Cannot convert value of type '(Int) -> Void' to expected argument type '(Any) -> Void'
I have two functions. 我有两个功能。 The first one is taking an Integer as parameter and returns nothing:
第一个是将Integer作为参数并且不返回任何内容:
func myIntFunction(_ arg: Int) -> Void {
print(arg)
}
The second one is taking a function of type (Any) -> Void
as parameter and returns nothing: 第二个是使用类型
(Any) -> Void
的函数(Any) -> Void
作为参数并且不返回任何内容:
func myAnyFunction(arg: @escaping (Any) -> Void) {
arg(5)
}
So there is something I am not catching here obviously as Int is a subset of Any right? 所以有一些我不明白的地方,因为Int是Any的子集吗?
So if I trying to use this code: 所以,如果我尝试使用此代码:
myAnyFunction(arg: myIntFunction)
I get a compilation error: 我收到编译错误:
Cannot convert value of type '(Int) -> Void' to expected argument type '(Any) -> Void'
and a suggestion to change my code into: 并建议将我的代码更改为:
myAnyFunction(arg: myIntFunction as! (Any) -> Void)
But then I get a runtime error as (Int) -> Void
cannot be casted into (Any) -> Void
但后来我得到一个运行时错误,因为
(Int) -> Void
不能被转换为(Any) -> Void
What am I not getting there? 我到底在哪里? I thought with a method/function asking for an argument of type
Any
, giving an Integer
as argument would work. 我想方法/函数要求一个类型为
Any
的参数,给一个Integer
作为参数是可行的。
So there is something I am not catching here obviously as
Int
is a subset ofAny
right?所以有一些我不明白的地方,因为
Int
是Any
的子集吗?
Right. 对。 However, since
Int
is a subset of Any
, a closure that expects Any
can be passed an Int
, but not the other way around (this cast is not possible either). 但是,由于
Int
是Any
的子集,因此期望Any
的闭包可以传递给Int
,而不是相反(这种强制转换也不可能)。
Imagine that it were possible to cast a closure taking an Int
to a closure taking Any
. 想象一下,有可能将一个闭包
Int
一个关闭,取Any
。 Now the users would be able to pass an object other than Int
to your closure, rendering type checking irrelevant. 现在,用户可以将除
Int
之外的对象传递给闭包,使得类型检查无关紧要。 That is why casting among closure types like that is not allowed. 这就是为什么不允许在这样的闭包类型中进行转换的原因。
You can create another closure that calls myIntFunction
, like this: 您可以创建另一个调用
myIntFunction
闭包,如下所示:
myAnyFunction(arg: {a -> Void in myIntFunction(a as! Int)})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.