Search code examples
iosswiftfunctioninfinite-loopvariable-declaration

Swift - causing an infinite loop while declaring a variable outside the function


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)
}

Solution

  • When it's outside the function it gets a value from the first group of elements so it will never be nil when the array is empty hence infinite loop , while inside the function it's value is decided according to current array elements

    It could work properly outside if you reset it like this at the beginning of the function

    var topItem: Int?
    func pickUpItem() -> Int? {
      topItem = nil
      ....
    }
    

    OR

    guard box.count > 0 else {
        return nil
    }