Search code examples
arraysswiftalgorithmfavorites

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


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]

Solution

  • 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
        }
    }