Reputation: 67
Just got this strange error when trying to write a stack with generic type in latest 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)'
}
}
Upvotes: 0
Views: 981
Reputation: 13661
The class is already generic, no need to make push generic too
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. 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]
.
Upvotes: 2