12

Running through the swift 2.0 documentation and Im trying to practice some stuff I learned in c++. One of which is the ability to modify array elements inside of my element which I am having trouble doing in 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
 }

Don't know what my error is because in the for-in loop, the scores less than 80 are being added but aren't being modified in the array I passed. Also would like to know how I can do this same thing using a nested function and not for-in loops.

3 Answers 3

21

I believe that using a for-in loop like this, your score variable is value copy of the array element, as opposed to a reference variable to the actual index of your array. I would iterate through the indices and modify scoresOfClass[index].

This should do what you're looking to do.

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
}

Also, why are you you using inout scoresOfClass when you're returning?

Sign up to request clarification or add additional context in comments.

3 Comments

Use ..< instead of -1.
Or even better: for index in scoresOfClass.indices.
thanks! this worked but @Mario Zannone 's solution is much more simple and cleaner
13

@ChrisMartin is correct: changing score you are simply changing a copy of the value, not the original in the array, and the approach with the index will work.

Another, more swifty solution is the following:

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

Here returnScoresWithCurve will return a modified array instead of changing the original. In my view this is a plus.

2 Comments

talking about code cleanliness, Thanks for the nice answer! Now Im on to figure out how I can use a nested function and do this problem
Better answer than the loopy one.
0

Another IMO beautiful solution in Swift:

 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
 } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.