【问题标题】:Swift - causing an infinite loop while declaring a variable outside the functionSwift - 在函数外部声明变量时导致无限循环
【发布时间】:2021-07-28 20:53:58
【问题描述】:

我最近开始学习 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)
}

【问题讨论】:

  • 在第一种情况下,您永远不会回到 topItemnil 的情况。当你在方法中声明它并且你得到 box.count > 0 时,你返回 nil。但是在外部声明时,它具有先前的值。所以当你在guard 中做return topItem 时,它不是零,所以while let 是有效的......

标签: ios swift function infinite-loop variable-declaration


【解决方案1】:

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

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

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

guard box.count > 0 else {
    return nil
}

【讨论】:

    猜你喜欢
    • 2012-02-06
    • 2015-11-09
    • 2011-04-10
    • 2016-12-05
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多