我正在为我的项目使用 swift。
我有一个名为 Instrument
的结构数组。后来我做了一个函数,它从数组中返回特定的 Instrument
。然后我想更改其属性之一的值,但此更改未反射(reflect)在数组内部。
我需要有这个数组来包含对里面元素的所有更改。您认为此处的最佳做法是什么?
- 将
Instrument
从struct
更改为class
。 - 以某种方式重写从数组返回
Instrument
的函数。
现在我使用这个函数:
func instrument(for identifier: String) -> Instrument? {
if let instrument = instruments.filter({ $0.identifier == identifier }).first {
return instrument
}
return nil
}
我从结构开始,因为众所周知,swift 是结构语言,我想了解何时使用 class
的 struct
。
谢谢
最佳答案
使用结构 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/