首页 > 解决方案 > Swift - 在函数外部声明变量时导致无限循环

问题描述

我最近开始学习 Swift,它是我的第一门编程语言。我在函数外部声明变量时遇到了困难,仍然无法弄清楚为什么它会导致无限循环。

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

但是,如果我在函数内声明变量,一切都很好。那是为什么?

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

标签: iosswiftfunctioninfinite-loopvariable-declaration

解决方案


当它在函数之外时,它从第一组元素中获取一个值,因此当数组为空时它永远不会为零,因此无限循环,而在函数内部它的值是根据当前数组元素决定的

如果在函数开始时像这样重置它,它可以在外面正常工作

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

或者

guard box.count > 0 else {
    return nil
}

推荐阅读