【问题标题】:I have two array. How Can I change different value in Array?我有两个数组。如何更改数组中的不同值?
【发布时间】:2022-01-13 15:17:39
【问题描述】:

我只将带有isSelected = true 的项目发送到favCountries。 在countries 中有来自该服务的所有国家/地区。 我想将来自服务的countriesfavCountries 进行比较,并在国家/地区数组中创建isSelected = true,以获取具有相同code 的国家/地区以及favCountries 中isSelected = true 的值。

如果favCountries数组中的代码和countries数组中的code匹配,我想让countries数组isSelected = true中的项值

我正在使用这个模型。

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]

【问题讨论】:

  • 不确定你的问题,但我猜let favCountries = countries.filter(\.isSelected)
  • 不,先生。 isSelected 属性并非来自服务。我自己添加了这个。对不起。我不懂英文。
  • 如果您添加一些示例并且预期的结果会更容易帮助您
  • 你必须使用类而不是结构,因为结构是值类型。
  • @cristian_064 这不正确,结构可以正常工作。

标签: arrays swift algorithm favorites


【解决方案1】:

不确定这是否是您再次提出的问题。但如果我理解正确,让你的CountryData 符合Equatable,迭代你的国家索引,如果favCountries 包含当前元素,将国家isSelected 属性更改为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
    }
}

【讨论】:

【解决方案2】:

如果我没看错的话,

  1. 您想循环访问var favCountries: [CountryData]var countries: [CountryData].code

  2. 如果在您的循环中,您的条件是 favCountries[$0] == countries[$0].code 为 TRUE,那么您想将 $0.isSelected 设置为 TRUE。

我的伪代码方法:

您可以遍历一个数组并检查每个对象代码是否存在于另一个数组中,如果存在,请将您的 isSelected 值设置为 true。

假设两个 [CountryData] 数组都是偶数,您可以尝试这样的操作:

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

祝你好运。

如果这有帮助,请告诉我!

【讨论】:

    猜你喜欢
    • 2019-08-06
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多