Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the values of an array using a for-in loop inside a function or a nested function?

Tags:

arrays

swift

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.

like image 659
Muhammad Avatar asked Jul 26 '15 23:07

Muhammad


People also ask

How do you change a value in an array?

To change the value of an object in an array:Call the findIndex() method to get the index of the specific object. Access the array at the index and change the property's value using dot notation. The value of the object in the array will get updated in place.

How do you use a loop inside an array?

For Loop to Traverse Arrays. We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.

How do you take the value out of a for loop?

have an hidden element say an input. set the value of it inside the loop with your value desired. call the change event along for the input element. Add a event listener for the change of input and get that value which is obviously outside the loop.

Can we use for in loop for array?

A for loop can be used to access every element of an array. The array begins at zero, and the array property length is used to set the loop end.


1 Answers

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?

like image 90
schrismartin Avatar answered Oct 05 '22 21:10

schrismartin