【发布时间】: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)
}
【问题讨论】:
-
在第一种情况下,您永远不会回到
topItem是nil的情况。当你在方法中声明它并且你得到 box.count > 0 时,你返回 nil。但是在外部声明时,它具有先前的值。所以当你在guard中做return topItem时,它不是零,所以while let是有效的......
标签: ios swift function infinite-loop variable-declaration