Home > Blockchain >  I have two array. How Can I change different value in Array?
I have two array. How Can I change different value in Array?

Time:01-14

I'm sending only items with isSelected = true into favCountries. There are all the countries that came from the service in countries. I want to compare the countries coming from the service with favCountries and make isSelected = true in the countries array for countries with the same code and the values that are isSelected = true in favCountries.

If the code in the favCountries array and the code in the countries array match, I want to make the item value in the countries array isSelected = true

I am using this model.

public struct CountryData: Codable {
  public let code: String?
  public let currencyCodes: [String]?
  public let name: String?
  public let wikiDataID: String?
  public var isSelected: Bool = false
}

var favCountries: [CountryData]
var countries: [CountryData]

CodePudding user response:

Not sure if that's what you are asking again. But if I understood correctly make your CountryData conform to Equatable, iterate your countries indices and if favCountries contains the current element change the countries isSelected property to true:


extension CountryData: Equatable {
    public static func ==(lhs: Self, rhs: Self) -> Bool {
        lhs.name == rhs.name // match the appropriate properties
    }
}

countries.indices.forEach { index in
    if favCountries.contains(countries[index]) {
        countries[index].isSelected = true
    }
}

CodePudding user response:

If I am reading the question correctly,

  1. you want to loop through var favCountries: [CountryData] and var countries: [CountryData].code

  2. IF IN your loop(s) you the condition where favCountries[$0] == countries[$0].code IS TRUE, THEN you want to set $0.isSelected to TRUE.

My approach in pseudo code:

You can loop through one array and check if each objects code exists in the other array and then if it does exist, set your isSelected value to true.

Assuming that both [CountryData] arrays are even you could try something like this:

FOR EACH country in CountryData {
  if let hasMatch = countries.contains({where: country.code == $0.code}) {
    country.isSelected = true
   
}

Good luck.

Let me know if this helps!

  •  Tags:  
  • Related