Oranutachi
Oranutachi

Reputation: 401

How to find same elements in different arrays Swift

Let's say I have an object model. I'm putting these objects into an array. I'm displaying these items in TableView. Then I filter this array using SearchController and put the filtered elements in another array and display it in the search, then I select some row. Then I cancel the search and the first array is displayed, but I want the row with the element that I selected in the search to be highlighted in it (the element from the second array). As I understand it, I need to compare two arrays and find the same elements in them and get the index of this element, then pass the index of this element to didSelectRow. How can i do this?

struct Model {
   var fileName: String
   var url: String
   init(fileName: String, url: String){
     self.fileName = fileName
     self.url = url
   }
}
let model1 = Model(fileName: "fileOne", url: "/path/fileOne")
let model2 = Model(fileName: "fileTwo", url: "/path/fileTwo")
let model3 = Model(fileName: "fileThree", url: "/path/fileThree")
let model4 = Model(fileName: "fileFour", url: "/path/fileFour")
...
let array: [Model] = [model1, model2, model3, model4]
var sortedArray: [Model] = []
...
//After search 
sortedArray = [model3, model4]
...
//I select element model3, in the sortedArray it has index 0, 
//but, let's say, I don't know what index doest it have in "array", how can I get it?
//I'd like to compare items by URL

Upvotes: 2

Views: 445

Answers (1)

JeremyP
JeremyP

Reputation: 86661

Use Array.firstIndex(where:) which returns the first index of an element that matches the criteria in the bool returning closure or nil if there isn't one.

guard let interestingIndex = array.firstIndex(where: { $0.url == model3.url })
    else { /* something's gone wrong */ }

Of course, you'd be better declaring url as an actual URL.

Upvotes: 3

Related Questions