[英]cannot invoke 'append' with an argument list of type '(T)'
Just got this strange error when trying to write a stack with generic type in latest playground. 尝试在最新的Playground中编写具有泛型类型的堆栈时遇到了这个奇怪的错误。 I really don't understand what's wrong here, can someone explain to me why I got this error?
我真的不明白这里出了什么问题,有人可以向我解释为什么我收到此错误吗?
class MyStack<T> {
var stack1 = [T]()
func push<T>(value: T) {
stack1.append(value) // Error: cannot invoke 'append' with an argument list of type '(T)'
}
}
The class is already generic, no need to make push generic too 该类已经是通用的,也无需使push通用
class MyStack<T> {
var stack1 = [T]()
func push(value: T) {
stack1.append(value)
}
}
When push
is declared as push<T>
, the generic parameter overrides the one defined on the class. 当
push
声明为push<T>
,泛型参数将覆盖在类上定义的参数。 So, if we were to rename the generic parameters, we'd get 因此,如果我们要重命名通用参数,我们将得到
class MyStack<T1> {
var stack1 = [T1]()
func push<T2>(value: T2) {
stack1.append(value) // Error: cannot invoke 'append' with an argument list of type '(T2)'
}
}
presented like this, it makes sense that we cannot push a T2
in [T1]
. 像这样呈现,我们不能在
[T1]
推T2
是有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.