Merge arrays with condition

后端 未结 3 2053
忘掉有多难
忘掉有多难 2021-01-20 02:30

I would like to merge two arrays with specific condition and update objects that they are containing.

First my struct that is in arrays:

struct Item          


        
3条回答
  •  情话喂你
    2021-01-20 03:13

    The following code does work independently by the order of the elements inside the 2 arrays

    firstArray = firstArray.map { (item) -> Item in
        guard
            let index = secondArray.index(where: { $0.id == item.id })
            else { return item }
        var item = item
        item.name = secondArray[index].name
        return item
    }
    

    "[Item(id: 1, name: "Bogdan", value: 3), Item(id: 2, name: "Max", value: 5)]\n"

    Update

    The following version uses the first(where: method as suggested by Martin R.

    firstArray = firstArray.map { item -> Item in
        guard let secondElm = secondArray.first(where: { $0.id == item.id }) else { return item }
        var item = item
        item.name = secondElm.name
        return item
    }
    

提交回复
热议问题