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.
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.
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With