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

Muh*_*ad 9 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
 }
Run Code Online (Sandbox Code Playgroud)

不知道我的错误是什么,因为在for-in循环中,正在添加小于80的分数,但是在我传递的数组中没有被修改.还想知道如何使用嵌套函数而不是for-in循环来做同样的事情.

小智 17

我相信使用像这样的for-in循环,你的得分变量是数组元素的值副本,而不是数组实际索引的引用变量.我会迭代索引并修改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
}
Run Code Online (Sandbox Code Playgroud)

另外,inout scoresOfClass你回来时为什么要用?

  • 甚至更好:`for scoreOfClass.indices`中的索引. (5认同)
  • 使用`.. <`而不是`-1`. (3认同)

Mar*_*one 12

@ChrisMartin是正确的:更改分数只是更改值的副本,而不是数组中的原始副本,并且索引的方法将起作用.

另一个更快速的解决方案如下:

func returnScoresWithCurve (scoresOfClass : [Int]) -> [Int] {
    return scoresOfClass.map { $0 < 80 ? $0 + 5 : $0 }
}
Run Code Online (Sandbox Code Playgroud)

这里returnScoresWithCurve将返回修改后的数组,而不是更改原始数组.在我看来,这是一个加号.