I am unsure what I am doing wrong here. I want to limit the values in var training to 1.0. I have set up a test where the two printed values should be different, but the value is not changed even though a number higher than 1.0 is found.
Code Block struct Horse { var training : [Float] } var myHorses = [ Horse(training: [1.5,0,0,0,0,0,0]), Horse(training: [0,0,0,0,0,0,0]), Horse(training: [0,0,0,0,0,0,0]) ] var horseIndex = 0 print(myHorses[horseIndex].training[0]) for var skills in myHorses[horseIndex].training { if skills > 1.0 { print("value > 1.0 found") skills = 1.0 } } print(myHorses[horseIndex].training[0])
Even when you apply var to the control variable of for-in statement, the variable holds the copy of each element of the Array as its initial value.
You cannot change the original Array when you just modify the control variable.
You need to write index based access when you want to modify the Array:
You cannot change the original Array when you just modify the control variable.
You need to write index based access when you want to modify the Array:
Code Block for index in myHorses[horseIndex].training.indices { if myHorses[horseIndex].training[index] > 1.0 { print("value > 1.0 found") myHorses[horseIndex].training[index] = 1.0 } }