我有一个看起来像这样的NSObject类
class MyItem : NSObject {
var id: Int
var name: String
//other init code here
}
我想要做的是,在其他课程中,当name
等于某事时,更新id
的值
现在MyViewController
var myItem = [MyItem]()
例如,如果myItem
为id=3
的内部数组,则将name
的值更新为"Ken"
。
我完全不知道该怎么做。有人可以给我一个提示吗?
答案 0 :(得分:0)
首先找到我要替换的对象的索引,然后使用索引将其替换为新值
if let row = myItem.index(where: {$0.id == yourId}) { // yourId 3
myItem[row].name = newValue
}
答案 1 :(得分:0)
这应该有效:
/// Changes The Name Of A MyItem Object Based On It's ID
///
/// - Parameters:
/// - id: Int
/// - name: String
func changeNameFromID(_ id: Int, to name: String){
//1. Get The Index Of The Item
guard let foundIndex = myItem.index(where: { $0.id == id }) else { return }
//2. Get The MyItem From The Array
let itemToAppend = myItem[foundIndex]
//3. Change Its Name
itemToAppend.name = name
}
然后你可以这样称呼它:
changeNameFromID(3, to: "Ken")