swift - 了解 for-in 循环

标签 swift

如何在 swift 中解释 for in 循环。

我把代码读成

for score in individualscores (5 numbers total) 
if score (5) is greater than 4 
teamscore = 0 + 3

else 
teamscore = 0+1 

实际的 Swift 代码:

let individualScores = [75,43,103,87,12]

var teamScore  = 0

for score in individualScores {
    if score > 4 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)

结果返回 15,但我期望是 5。有人可以解释这段代码吗?

最佳答案

为什么你期望 5?代码按预期工作。在 For-in 循环中,迭代序列中的所有对象(它可以是数组、字典、范围、字符串等)。由于它们都大于 4,因此您的循环运行了 5 次,并且 teamscore 在每次迭代中递增 3,从而得到 15。从角度来看,修改代码如下:

let individualScores = [75,43,103,87,12]

var teamScore  = 0

for score in individualScores {
    print("Currently the value in score is: \(score)")
    if score > 4 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)

您将看到以下打印语句:

Currently the value in score is: 75
Currently the value in score is: 43
Currently the value in score is: 103
Currently the value in score is: 87
Currently the value in score is: 12

所以首先循环不保留计数器,它只使用数组的长度。它知道它必须迭代 5 个项目。第一项是 75,它大于 4,因此团队得分增加 3。下一项是 43,与 75 的情况相同。依此类推。这就是您获得 15 的方式。

您的困惑似乎是 score 将具有每个项目的索引,因此它将变为 0、1、2、3、4。由于这些都不大于 4,因此控件将在 else 条件下失败并将 teamscore 增加 1。这就是您得出结论的方式,即 中的结果必须为 5团队得分。您的想法与它的工作原理之间的比较如下:

let individualScores = [75,43,103,87,12]

var teamScore  = 0
var indexScore = 0
for (index, score) in zip(individualScores.indices, individualScores) {
    print("Found \(score) at Index \(index)")

    //What you had in mind how it works
    if index > 4 {
        indexScore += 3
    } else {
        indexScore += 1
    }

    //How it actually works
    if score > 4 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print("Team Score: \(teamScore)")
print("Index Score: \(indexScore)")

现在您的打印语句将是:

Found 75 at Index 0
Found 43 at Index 1
Found 103 at Index 2
Found 87 at Index 3
Found 12 at Index 4
Team Score: 15
Index Score: 5

如您所料,指数得分为 5,但团队得分为 15。

那是因为 for-in 迭代的是序列的值,即 75、43、103、87 和 12,而不是它们的索引。

改进迭代代码的致谢:Robb MayoffAlexander

关于swift - 了解 for-in 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56533369/

相关文章:

ios - 如何将 NSURL session 进度添加到 TableView 单元格

Swift 3,在 Poloniex 交易 Api 中获取 - "error": Invalid command

ios - 无效的 Swift 支持--iTunes 连接错误 (Swift 2/Xcode 7)

garbage-collection - swift 如何处理确定性终结?

iOS Swift - 调试内存泄漏

ios - CGAffineTransform 反转 : singular matrix Error

ios - 在不缩小内容的情况下调整 Sprite 大小

ios - 当状态更改时,如何防止 SceneKit 场景重新渲染不佳?

ios - 当我使用自定义 UIColors 时标签的文本颜色没有改变

For 循环中的 IOS 动画。调整了每个延迟但仍然有问题