Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ios

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?

like image 985
Utku Dalmaz Avatar asked Jun 28 '16 19:06

Utku Dalmaz


People also ask

How do I change the value of an array in Swift?

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.

How do you modify an array of objects?

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.

How do you check if an array contains an item Swift?

The contains() method returns: true - if the array contains the specified element. false - if the array doesn't contain the specified element.


1 Answers

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 } 
like image 61
Jenel Ejercito Myers Avatar answered Sep 28 '22 09:09

Jenel Ejercito Myers