Kle*_*men 9 arrays struct swift
我正在为我的项目使用swift.
我有一个名为的结构数组Instrument.后来我创建了一个Instrument从数组返回特定的函数.然后我想在其中一个属性上更改值,但此更改不会反映在数组中.
我需要让这个数组包含内部元素的所有更改.您认为这里的最佳做法是什么?
Instrument从struct到class.Instrument从数组返回的函数.现在我使用这个功能:
func instrument(for identifier: String) -> Instrument? {
if let instrument = instruments.filter({ $0.identifier == identifier }).first {
return instrument
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
我开始与结构,因为迅速被称为是语言结构,我想学习时使用struct的class.
谢谢
Owe*_*wen 13
使用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)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5674 次 |
| 最近记录: |