How to change data in an array using a variable?

I want to change some properties in my array. I recently discovered that I am only able to do this if I directly specify the number of the element in the array I am working with. This is tricky because I always assumed you could edit an array using a variable. I have been using a variable to save myself a lot of code. In some view controllers, the array can have hundreds of items... my var is a workaround that uses the button tag to identify the horse that is selected for editing

Code Block
import UIKit
struct Horse{
    var name: String
    var age: Int
}
var myHorses = [
    Horse(name: "Billy", age: 3),
    Horse(name: "Merc", age: 5)
]
//horse selected for editing
var currentHorse = myHorses[0]
//tag of the button that is pressed
var horseIndex = sender.tag
//trying to edit age
currentHorse.age = 10
//I thought these would be the same
print(myHorses[1].age)
print(merc.age)


Answered by Claude31 in 651847022
On line 17, you create a new instance of Horses where you copy myHorses[0]

But it does not point to myHorses[0], because Horse is a struct, hence copied by value, not reference.

If you change struct with class, you'll get what you expect:
Code Block
class Horse {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}

edit: If I use "myHorses[horseIndex]" instead of "currentHorse", this worked in playgrounds. Testing in the app now

Accepted Answer
On line 17, you create a new instance of Horses where you copy myHorses[0]

But it does not point to myHorses[0], because Horse is a struct, hence copied by value, not reference.

If you change struct with class, you'll get what you expect:
Code Block
class Horse {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}

Yes this explains a few bugs in my app. Thanks for the explanation! Currently replacing all of the "currentHorse" with "myHorses[horseIndex]"
How to change data in an array using a variable?
 
 
Q