【问题标题】:How do I change the values of an array using a for-in loop inside a function or a nested function?如何在函数或嵌套函数中使用 for-in 循环更改数组的值?
【发布时间】:2015-07-26 23:11:05
【问题描述】:

浏览 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 循环来做同样的事情。

【问题讨论】:

    标签: arrays swift


    【解决方案1】:

    我相信使用这样的 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

    【讨论】:

    • 使用..&lt; 而不是-1
    • 或者更好:for index in scoresOfClass.indices.
    • 谢谢!这行得通,但@Mario Zannone 的解决方案更加简单和清洁
    【解决方案2】:

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

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

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

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

    【讨论】:

    • 谈论代码清洁度,感谢您的精彩回答!现在我要弄清楚如何使用嵌套函数来解决这个问题
    • 比循环的更好的答案。
    【解决方案3】:

    Swift 中另一个 IMO 漂亮的解决方案:

     var scoreOfStudents = [86, 93, 68, 78, 66, 87, 80]
    
     func returnScoresWithCurve (inout scoresOfClass : [Int]) -> [Int] {
          for (index, score) in scoresOfClass.enumerated() {
              if score < 80 {
                  scoresOfClass[index] = score + 5
              }
          }
          return scoresOfClass
     } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 2021-03-03
      相关资源
      最近更新 更多