运行
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变量是数组元素的值副本,而不是数组实际索引的引用变量.我会遍历索引并
修改scoreOfClass [index].
这应该做你想做的事情.
- var scoreOfStudents = [86,80]
-
- func returnscoresWithCurve(inout scoresOfClass: [Int]) -> [Int] {
- for index in scoresOfClass.indices {
- if scoresOfClass[index] < 80 {
- scoresOfClass[index] += 5
- }
- }
- return scoresOfClass
- }
另外,你为什么要在返回时使用inout scoresOfClass?