arrays - 如何更改数组中结构的值?

标签 arrays swift struct

我正在为我的项目使用 swift。

我有一个名为 Instrument 的结构数组。后来我做了一个函数,它从数组中返回特定的 Instrument。然后我想更改其属性之一的值,但此更改未反射(reflect)在数组内部。

我需要有这个数组来包含对里面元素的所有更改。您认为此处的最佳做法是什么?

  • Instrumentstruct 更改为 class
  • 以某种方式重写从数组返回 Instrument 的函数。

现在我使用这个函数:

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

我从结构开始,因为众所周知,swift 是结构语言,我想了解何时使用 classstruct

谢谢

最佳答案

使用结构 Instrument 数组,您可以获得具有特定标识符的 Instrument 的索引,并使用它来访问和修改 Instrument 的属性。

struct Instrument {
    let identifier: String
    var value: Int
}

var instruments = [
    Instrument(identifier: "alpha", value: 3),
    Instrument(identifier: "beta", value: 9),
]

if let index = instruments.index(where: { $0.identifier == "alpha" }) {
    instruments[index].value *= 2
}

print(instruments) // [Instrument(identifier: "alpha", value: 6), Instrument(identifier: "beta", value: 9)]

关于arrays - 如何更改数组中结构的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41665629/

相关文章:

swift - 由于缺少依赖项,Moscapsule 阻止为 watchOS 构建应用程序

C++ 以独立于平台的方式序列化和压缩 vector<structs>

swift - iOS9:UITextField 不允许复制/粘贴

Java Arrays.fill()

java - 在Java中切换对象数组中的最小值和最大值

javascript - 如何输出数组中所需的元素

ios - 如何解决 React Native iOS 中的 'Undefined symbols for architecture armv7'?

c - 结构数组错误

c - 由于对齐而在 C 结构中查找孔

java - 用空值填充数组