数组 – 如何更改数组中struct的值?

前端之家收集整理的这篇文章主要介绍了数组 – 如何更改数组中struct的值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为我的项目使用 swift.

我有一个名为Instrument的结构数组.后来我创建了一个从数组中返回特定Instrument的函数.然后我想在其中一个属性上更改值,但此更改不会反映在数组中.

我需要让这个数组包含内部元素的所有更改.您认为这里的最佳做法是什么?

>将Instrument从struct更改为class.
>以某种方式重写从数组返回Instrument的函数.

现在我使用这个功能

  1. func instrument(for identifier: String) -> Instrument? {
  2. if let instrument = instruments.filter({ $0.identifier == identifier }).first {
  3. return instrument
  4. }
  5. return nil
  6. }

我从结构开始,因为已知swift是结构语言,我想学习何时使用类的结构.

谢谢

使用struct Instrument数组,您可以获取具有特定标识符的Instrument的索引,并使用它来访问和修改Instrument的属性.
  1. struct Instrument {
  2. let identifier: String
  3. var value: Int
  4. }
  5.  
  6. var instruments = [
  7. Instrument(identifier: "alpha",value: 3),Instrument(identifier: "beta",value: 9),]
  8.  
  9. if let index = instruments.index(where: { $0.identifier == "alpha" }) {
  10. instruments[index].value *= 2
  11. }
  12.  
  13. print(instruments) // [Instrument(identifier: "alpha",value: 6),value: 9)]

猜你在找的Swift相关文章