How to do `+=` for KeyValuePairs?

I need to concatenate elements of [KeyValuePairs] into one big KeyValuePairs:

var kv1: KeyValuePairs = [
    1: 1,
    2: 2
]

let kv2: KeyValuePairs = [
    1: 1,
    2: 2
]

kv1 += kv2  // error: Binary operator '+=' cannot be applied to two 'KeyValuePairs<Int, Int>' operands

it seems there is no += for KeyValuePairs. Anyway, I couldn't figure out how to define it:

func += <K, V>(lhs: inout KeyValuePairs<K, V>, rhs: KeyValuePairs<K, V>) {
    for e in rhs {
        lhs.append(e)   // does this work?
    }
}

Help me, please :pray::star_struck:

I'm almost certain (well, almost) that KeyValuePairs is meant to be a non-mutating structure, similar to StaticString. It may make more sense if you convert them to an array of tuple.

Ok, I understand. So convert KeyValuePairs to [(Key, Value)]:

func += <K, V>(lhs: inout [(K, V)], rhs: KeyValuePairs<K, V>) {
    lhs += rhs.map { ($0.key, $0.value) }
}

You seem to be given an already-Array of key value pairs. Using flatMap might be more convenient.

1 Like
Terms of Service

Privacy Policy

Cookie Policy