I can't quite figure out how to declare "if optional" on a stack using class on Swift. Here's the generic code that I have for a stack on Swift using class (the book uses struct but I was told to use class).
class Stack {
var items = [String]()
func push(item: String) {
items.append(item)
}
func pop() -> String {
return items.removeLast()
}
func length() -> Int {
return items.count
}
}
I create an instance of Stack:
var stringStack = Stack()
...
stringStack.pop()
when I pop, the stack removes the last item. I want to make it so that if I do pop(0), the stack will remove the first item, but if I just do pop(), the stack only removes the last item. I was thinking of making an optional value with if ... return items.removeAtIndex(0) or else items.removeLast(). I can't seem to get the syntax right and I keep getting error. I was able to make it so that pop(0) removes the first item in the stack, but I get error if I do pop(). If someone can show me a code to do what I want to do that would be really helpful. I'm still very, very new at coding and I don't know much. Sorry for the embarrassment!