数组 – 如何更改数组中struct的值?
发布时间:2020-12-14 05:21:14 所属栏目:百科 来源:网络整理
导读:我正在为我的项目使用 swift. 我有一个名为Instrument的结构数组.后来我创建了一个从数组中返回特定Instrument的函数.然后我想在其中一个属性上更改值,但此更改不会反映在数组中. 我需要让这个数组包含内部元素的所有更改.您认为这里的最佳做法是什么? 将In
我正在为我的项目使用
swift.
我有一个名为Instrument的结构数组.后来我创建了一个从数组中返回特定Instrument的函数.然后我想在其中一个属性上更改值,但此更改不会反映在数组中. 我需要让这个数组包含内部元素的所有更改.您认为这里的最佳做法是什么? >将Instrument从struct更改为class. 现在我使用这个功能: func instrument(for identifier: String) -> Instrument? { if let instrument = instruments.filter({ $0.identifier == identifier }).first { return instrument } return nil } 我从结构开始,因为已知swift是结构语言,我想学习何时使用类的结构. 谢谢
使用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),value: 9)] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |