ios - 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)
}
解决方案
当它在函数之外时,它从第一组元素中获取一个值,因此当数组为空时它永远不会为零,因此无限循环,而在函数内部它的值是根据当前数组元素决定的
如果在函数开始时像这样重置它,它可以在外面正常工作
var topItem: Int?
func pickUpItem() -> Int? {
topItem = nil
....
}
或者
guard box.count > 0 else {
return nil
}
推荐阅读
- spring - @SpringBootConfiguration,运行 mvn clean install 时需要使用@ContextConfiguration
- class - Lua 类方法
- python - Pandas 中所有先前行的条件运行计数
- python - 如何让pyautogui的点击在mac上工作?
- python - 如何在 Django 中为点对点交易建模?
- jquery - 如何使用两个不同的 JQuery 函数?
- android - 将 gatt 特性写入 BLE 设备时出现问题
- javascript - SQLITE 查询的“排序依据”结果未排序
- python - Pypyodbc TabError:缩进中制表符和空格的不一致使用
- php - 过滤不过滤