arrays - 如何在函数或嵌套函数内使用 for-in 循环更改数组的值?

标签 arrays swift

浏览 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/

相关文章:

java - 如何去掉 Arrays.toString() 返回的大括号和逗号?

Swift: '(String) -> AnyObject?' 没有名为 'subscript' 的成员

c++ - 不能在数组上使用 .begin() 或 .end()

javascript - 递归函数中的 Array.prototype.reduce 产生意外结果

javascript - 在javascript中将数组转换为嵌套对象

swift - Realm 通知不会触发初始值

ios - UISearchBar 打开第二个 TableView 没有结果

swift - 如何平滑地更改不会设置动画的 SCNCamera 的 FoV?

ios - 导航栏背景图像未扩展到搜索栏

php - 检查两个数组中的任何匹配项