Utku Dalmaz Utku Dalmaz - 5 months ago 29
Swift Question

Find an item and change value in custom object array - Swift

I have this class

class InboxInterests {

var title = ""
var eventID = 0
var count = ""
var added = 0

init(title : String, eventID : NSInteger, count: String, added : NSInteger) {
self.title = title
self.eventID = eventID
self.count = count
self.added = added

}
}


And i use it like this

var array: [InboxInterests] = [InboxInterests]()


Add item

let post = InboxInterests(title: "test",eventID : 1, count: "test", added: 0)
self.array.append(post)


I want to find the index by
eventID
key and change the value of
added
key in the same index

How is that possible?

Answer

Use filter and first to find the value:

array.filter({$0.eventID == id}).first?.added = value

In this you: - filter the array down to elements that match the event ID - pick the first result, if any - then set the value