浏览 swift 2.0 文档,我正在尝试练习我在 C++ 中学到的一些东西。其中之一是能够修改我的元素内部的数组元素,我在 swift 中遇到了麻烦。
var scoreOfStudents = [86, 93, 68, 78, 66, 87, 80]
func returnScoresWithCurve (inout scoresOfClass : [Int]) -> [Int] {
for var score in scoresOfClass {
if score < 80 {
score += 5
}
}
return scoresOfClass
}
不知道我的错误是什么,因为在 for-in 循环中,小于 80 的分数被添加但没有在我传递的数组中被修改。还想知道如何使用嵌套函数而不是 for-in 循环来做同样的事情。
最佳答案
我相信使用这样的 for-in 循环,您的 score 变量是数组元素的值副本,而不是指向数组实际索引的引用变量。我会遍历索引并修改 scoresOfClass[index]
。
这应该可以满足您的需求。
var scoreOfStudents = [86, 93, 68, 78, 66, 87, 80]
func returnScoresWithCurve(inout scoresOfClass: [Int]) -> [Int] {
for index in scoresOfClass.indices {
if scoresOfClass[index] < 80 {
scoresOfClass[index] += 5
}
}
return scoresOfClass
}
另外,你为什么在返回时使用 inout scoresOfClass
?
关于arrays - 如何在函数或嵌套函数内使用 for-in 循环更改数组的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31642892/