Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack implementation in Swift

Tags:

stack

ios

swift

I'm new to Swift and iOS programming.

I'm trying to test out a simple algorithm and need an array of Stacks. Don't have to be anything fancy (Stacks of Ints will do).

I got the Stack implementation from The Swift Programming Language documentation:

struct IntStack {
    var items = [Int]()
    mutating func push(item: Int) {
        items.append(item)
    }
    mutating func pop() -> Int {
        return items.removeLast()
    }
    mutating func count() -> Int {
        return items.count
    }
    mutating func show() {
        println(items)
    }
}

The count and show functions are my contribution. But when I try to declare an array of Stacks I get an error...

var lines = IntStack()[5]

"IntStack" does not have a member named subscript

I'm guessing it has something to do with Optionals but can figure out what it is.

Any help?

like image 330
Plinio Vilela Avatar asked Jul 16 '15 18:07

Plinio Vilela


2 Answers

Details

  • Swift 5.1, Xcode 11.3.1

Generic Stack Implementation

Stackable protocol

protocol Stackable {
    associatedtype Element
    func peek() -> Element?
    mutating func push(_ element: Element)
    @discardableResult mutating func pop() -> Element?
}

extension Stackable {
    var isEmpty: Bool { peek() == nil }
}

Stack

struct Stack<Element>: Stackable where Element: Equatable {
    private var storage = [Element]()
    func peek() -> Element? { storage.last }
    mutating func push(_ element: Element) { storage.append(element)  }
    mutating func pop() -> Element? { storage.popLast() }
}

extension Stack: Equatable {
    static func == (lhs: Stack<Element>, rhs: Stack<Element>) -> Bool { lhs.storage == rhs.storage }
}

extension Stack: CustomStringConvertible {
    var description: String { "\(storage)" }
}
    
extension Stack: ExpressibleByArrayLiteral {
    init(arrayLiteral elements: Self.Element...) { storage = elements }
}

Usage

var stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek())
print(stack.pop())
print(stack)
print(stack == Stack<Int>())
stack = [3,2,1]
print(stack)
like image 181
Vasily Bodnarchuk Avatar answered Sep 29 '22 11:09

Vasily Bodnarchuk


There's no problem with what you're doing there - that's just not the syntax for declaring an array. If you want an array of 5 stacks, you can do this:

[IntStack(), IntStack(), IntStack(), IntStack(), IntStack()]

Or, you can initialise the array like this:

Array(count: 5, repeatedValue: IntStack())

Also, you don't need to mark your functions as mutating unless they actually mutate the structure - so count() and show() don't need it.

like image 44
oisdk Avatar answered Sep 29 '22 13:09

oisdk