简体   繁体   中英

Compare data between two Arrays containing custom Swift Objects

I have some data I have received through an API that return JSON to me. I know I can fetch it and store relevant info from the API into my iOS app. But only while the app is running. IE I have not implemented YET how to store the info fetched from the API into UserDefalults. Working on this feature I ran into a problem.

I have two Arrays that keeps track of my data. The first Array is the Array I want to store in UserDefaults when I have fetch my data. This one is called "lenders" and keeps LenderData The second Array is my temporary Array. It contains the same type of objects, and this is the one I want to populate with data from the API and then compare to my existing Array "lenders".

I want to check if the "lenders" Array contains any object that has the same id as the object I'm looking at in the "lendersTemp" array. If the lenders Array does not contain any LederData object with the id of the tempLender we are currently looking at, we add the tempLender into the lenders Array. How would I go about doing this?

My current (non-working) solution is as follows:

var lenders = [LenderData]()
var lendersTemp = [LenderData]()

...
// Get JSON DATA
...

for tempLender in self.lendersTemp {
    if !self.lenders.contains(where: {$0.id == tempLender.id}) {
        self.lenders.append(tempLender)
     }
}

EDIT: My view did load method:

var lenders = [LenderData]()
var lendersTemp = [LenderData]()

override func viewDidLoad() {
    super.viewDidLoad()

    downloadJSON {
        self.myTableView.reloadData()
    }

    self.myTableView.rowHeight = 90
    myTableView.delegate = self
    myTableView.dataSource = self
}

I figured it out with some help! So this is my answer to my own question!

My problem was that getting data from my API is done with an asyc method. And I tried to do comparison after the reload method was called on my TableView. So I did not populate the array the tableview is getting data from, before after the reloadData() had been called and therefore it seemed like my tableview and comparison algorithm, did not work, when in fact it did!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM