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?


Solution 1:

For me, the above answer did not work. So, what I did was first find the index of the object that I want to replace then using the index replace it with the new value

if let row = self.upcoming.index(where: {$0.eventID == id}) {
       array[row] = newValue
}

In Swift 5.0:

if let row = self.upcoming.firstIndex(where: {$0.eventID == id}) {
       array[row] = newValue
}

Solution 2:

Since you are using a class, use filter and first to find the value:

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

In this you:

  1. filter the array down to elements that match the event ID
  2. pick the first result, if any
  3. then set the value

This works since classes are pass by reference. When you edit the return value from array.filter({$0.eventID == id}).first?, you edit the underlying value. You'll need to see the answers below if you are using a struct

EDIT: In Swift 3 you can save yourself a couple of characters

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

EDIT: Swift 4.2:

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