Merge arrays with condition

后端 未结 3 2094
忘掉有多难
忘掉有多难 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:12

    The map function cannot directly mutate its elements. And since you're using structs (passed by value), it wouldn't work anyway, because the version you see in $0 would be a different instance than the one in the array. To use map correctly, I'd use a closure like this:

    fisrtArray = zip(fisrtArray, secondArray).map() {
       return Item(id: $0.id, name: $1.name, value: $0.value)
    }
    

    This produces the result you're expecting.

    Now, if your structs were objects (value types instead of reference types), you could use forEach and do the $0.name = $1.name in there.

提交回复
热议问题