0

My model class is as below :

struct Job: Decodable, Equatable, Hashable {
   var id: Int?
   var status: String?
   var priority: String?
}

I have 2 array of objects(job) as :

 var jobModel = [Job]()
 var filteredJobModel = [Job]()

Case : jobModel has 5 elements. filteredJobModel has 2 elements( subset of jobModel ). In filteredJobModel, the value for status for both objects has been changed by search operation. I would like to update the jobModel back with filteredJobModel, where the object matches the id attribute.

Is there any way by which I can achieve this case? I would have been able to use filter & map for [String], but, I would like to know how to implement higher order functions for array of custom objects.

1 Answer 1

1
for (index, job) in idsJobModel.enumerated() {
    if let match = arrFiltetered.first( where: {job.id == $0.id} ) {
     idsJobModel[index] = match
   }
}

Or if you prefer using map:

idsJobModel = idsJobModel.map {
    let myID = $0.id
    if let match = arrFiltetered.first( where: {myID == $0.id} ) {
        return match
    } else {
        return $0
    }
}

Either version of the code above will have O(n²) performance, so it will get dramatically slower as your arrays get larger than ≈30 elements. It would need to be tweaked to perform well on larger arrays.

Sign up to request clarification or add additional context in comments.

2 Comments

Assuming the id value in idsJobModel is always unique (and never nil), you could improve the performance of the above by mapping the arrFiltetered array into a dictionary using the id as a key. you'd then loop through idsJobModel , do a dictionary lookup of each ID, and replace the entry in idsJobModel if found as above (dictionary lookups are almost O(1), so that would improve your performance to roughly O(n), a dramatic improvement.
Even if your id values are not unique you could implement a custom hash function that excludes your (changeable) status property and use the hash as your dictionary key in the above speed optimization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.