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)
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:
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 } }