Stack injection in Swift

I am new to Swift and iOS programming.

I am trying to test a simple algorithm and need an array of stacks. You don't have to be interesting (Stacks of Ints will do).

I got the Stack implementation from 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 counting 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" has no index member

I assume it has something to do with Optionals, but can figure out what it is.

any help?

+4


source to share


3 answers


There is no need to declare the size of the stack when initializing it. Jus, naming it, should be enough.

var lines = IntStack()

      



Also note that your count () and show () methods should not mutate as they do not change the structure in any way.

+2


source


No problem with what you're doing there - it's just not the syntax for declaring an array. If you want a 5 stack array, you can do this:

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

      

Or you can initialize the array like this:



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

      

Also, you don't need to specify your functions as mutating

if they don't actually mutate the structure - count()

and therefore show()

don't need it.

+1


source


Here is a stack implementation using Swift Generics,

struct Fruit {
let fruitName : String
let color : String
init(_ name: String,_ color: String) {
    self.fruitName = name
    self.color = color
}
}

let fruit1 = Fruit("Apple", "Red")
let fruit2 = Fruit("Grapes", "Green")

let fruitStack = Stack<Fruit>()
fruitStack.push(fruit1)
fruitStack.push(fruit2)

let fruitFfromStack = fruitStack.pop()
print("Fruit popped from Stack, Name : \(String(describing: fruitFfromStack?.fruitName)) ,Color : \(String(describing: fruitFfromStack?.color))")
let fruitFfromStack1 = fruitStack.pop()
print("Fruit popped from Stack, Name : \(String(describing: fruitFfromStack1?.fruitName)) ,Color : \(String(describing: fruitFfromStack1?.color))")

      

The complete code is here:

https://reactcodes.blogspot.com/2019/01/generic-stack-implementation-with.html

0


source







All Articles