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?
Swift Array – Replace Element To replace an element with another value in Swift Array, get the index of the match of the required element to replace, and assign new value to the array using the subscript.
To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is.
The contains() method returns: true - if the array contains the specified element. false - if the array doesn't contain the specified element.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With