【问题标题】:how to find element of an Array that has the same property with element from another array and change it accordingly?如何找到与另一个数组中的元素具有相同属性的数组元素并相应地更改它?
【发布时间】:2018-11-27 10:25:13
【问题描述】:

我有如下代码的产品类:

class Product {
    var productID = ""
    var hasBeenAddedToWishList = false
}

然后我有两个产品数组

let wishListedProduct = [productx,producty,productz] // from core data
let productList = [productx,producty,productz] // from server

如果用户之前已将产品添加到核心数据中的愿望清单,我想给出填充的爱图标。

所以我想在上面的数组之间进行循环,所以如果wishListedProduct的第一个索引中的产品与productList的第一个索引具有相同的ID,那么我需要更改@987654327的属性@ 为真。该怎么做?

我已经尝试使用下面的代码,但我无法得到我想要的

        for i in theWishListProducts {

                products.map {

                    if $0.productID == i.productID {
                        $0.hasBeenAddedToWishList = true
                    }

                }
            }

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    例如:

    let wishListedProduct : [Product] = // whatever
    let productList : [Product] = // whatever
    let wishListedIds = wishListedProduct.map {$0.productID}
    for product in productList {
        if wishListedIds.contains(product.productID) {
            product.hasBeenAddedToWishList = true
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 1970-01-01
      • 2014-01-03
      • 2020-03-30
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      相关资源
      最近更新 更多