为什么不能使用“ helper”变量更新数组中的对象?

时间:2019-05-21 16:30:41

标签: arrays swift updating

出于好奇,我要求这样做是为了了解Swift。

我正在尝试更新位于另一个类中的数组中的对象。

我有两种情况(另一种​​有效,另一种无效)

  1. 工作解决方案:
    Data.tripModels[0].title = "lol"
  1. 不起作用:
    var trip = Data.tripModels[0]
    trip.title = "lol"

为帮助您理解:

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

为什么2.不起作用? :(

1 个答案:

答案 0 :(得分:1)

2。不起作用,因为由于值语义( tripmodel 的类型是结构),线

var trip = Data.tripModels[0] 

将数组中该项的副本分配给trip

trip.title = "lol"

更新副本,但不更新数组中的项目。

请阅读Swift语言指南中的Structures and Enumerations are Value Types

相关问题