0

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

1 Answer 1

2

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].

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! It really helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.