I have started learning Swift recently and it was my first coding language. I encountered a difficulty while declaring a variable outside the function and still couldn't figure out why it caused an infinite loop.
func addItem(item: Int) {
box.append(item)
}
var topItem: Int?
func pickUpItem() -> Int? {
// var topItem: Int?
guard box.count > 0 else {
return topItem
}
topItem = box[box.count - 1]
box.remove(at: box.count - 1)
return topItem
}
var box: [Int] = []
addItem(item: 667)
addItem(item: 651)
addItem(item: 604)
while let num = pickUpItem() {
print(num)
}
However, if I declared the variable inside the function, everything went fine. Why was that?
func addItem(item: Int) {
box.append(item)
}
//var topItem: Int?
func pickUpItem() -> Int? {
var topItem: Int?
guard box.count > 0 else {
return topItem
}
topItem = box[box.count - 1]
box.remove(at: box.count - 1)
return topItem
}
var box: [Int] = []
addItem(item: 667)
addItem(item: 651)
addItem(item: 604)
while let num = pickUpItem() {
print(num)
}