Search code examples
arraysswiftupdating

Why Can't I Update an Object in Array using a "helper" Variable?


I'm asking this out of curiosity to understand Swift.

I'm trying to update objects in an array situated in another class.

I have two cases (the other one works, and other one doesn't)

  1. Working solution:
    Data.tripModels[0].title = "lol"
  1. Not working:
    var trip = Data.tripModels[0]
    trip.title = "lol"

To help you understand:

    Data = the other class
    tripModels = the array in Data class, holding the objects
    title = a property of tripModel in tripModels array

Why is the 2. not working? :(


Solution

  • The 2. does not work because due to value semantics (the type of tripmodel is a struct) the line

    var trip = Data.tripModels[0] 
    

    assigns a copy of the item in the array to trip and

    trip.title = "lol"
    

    updates the copy but not the item in the array.

    Please read Structures and Enumerations are Value Types in the Swift Language Guide