0

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? :(

4
  • Are the items in the tripModels array instances of a struct? Commented May 21, 2019 at 16:44
  • @vacawama yes :) Commented May 21, 2019 at 17:00
  • Then @vadian's answer explains the issue. structs are value types, so you're updating a copy. Commented May 21, 2019 at 17:02
  • @vacawama Thank you for your help! I'm new to struct s ... Commented May 21, 2019 at 17:07

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for your fast response. Now that you said it it makes sense to me also... Would it work if I would leave the [0] out of the variable? Or would it just save a copy of the whole array instead of a reference?
It creates also a copy of the array. But you can reassign the changed item: var trip = Data.tripModels[0]; trip.title = "lol"; Data.tripModels[0] = trip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.