Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Joyce Ryu
1,124 PointsAbout Queue and Stack - do we have lectures on this topic?
I am taking iOS swift development course, and looking for Queue and Stack problem solving but cannot find one. In teamtreehouse, do we lectures on this ? If there is, what course can I find it?
1 Answer
Richard Lu
20,185 PointsHi Hee Eun,
What I understand is that you're looking for a course to learn more about the Queue/Stack data structure in Swift, and from my knowledge I don't think there is one.
The problem with Swift using the queue/stack data structure is that there isn't an actual struct like an array (yes, I mean struct). The good news is you can easily build them!
Here's a generic stack implementation with the push and pop capabilities.
struct Stack<T> {
private var stack = [T]()
mutating func push(newElement: T) {
stack.append(newElement)
}
mutating func pop() -> T? {
return stack.popLast()
}
func peek() -> T? {
return stack.last
}
}
Here's a generic queue implementation.
struct Queue<T> {
private var queue = [T]()
mutating func add(newElement: T) {
queue.append(newElement)
}
mutating func remove() -> T? {
return queue.count > 0 ? queue.removeFirst() : nil
}
func peek() -> T? {
return queue.first
}
}
If you'd like me to break down what the code is doing please let me know. Good luck. Happy coding! :)
Joyce Ryu
1,124 PointsJoyce Ryu
1,124 PointsWow I didn't expect this much! Thank you very much !
Joyce Ryu
1,124 PointsJoyce Ryu
1,124 Points'''html
struct Stack {
}
Is this right way to make stack coding?
Richard Lu
20,185 PointsRichard Lu
20,185 PointsHi Hee Eun,
Your code is close to correct if you just want to mimic the behavior of what's going on with UIViewControllers using strings. Using the stack that I've provided above, you must provide a type.
var newStack = Stack<String>()to find the top item in your stack, I've implemented it as the method 'peek'
Joyce Ryu
1,124 PointsJoyce Ryu
1,124 PointsCan you write whole codes using what I posted below?? I get all rows error
Richard Lu
20,185 PointsRichard Lu
20,185 PointsHi Hee Eun,
Sorry for the delay in response. Here's your code written out to be compatible for Swift 2.0.