WH48
WH48

Reputation: 777

Updating each one of the keys inside an array of tuples

I have an array of tuples that each contain a key and a value. At the moment I am filtering all the tuples that keys are larger than an Int. Then using this filtered array to update each one of the of their keys but keeping the same values.

The way I'm doing it currently doesn't work as it just removes all the tuples that keys are equal to the filtered keys before I have appended the new keys, which is understandable.

What I would like to do is, instead of removing them and then adding them back, just update each one of their keys, however with me being relatively new to coding I have no idea how to do this. As I guess its something to do with compactMap or flatMap but again, have no idea how to do this.

Any help is greatly appreciated, many thanks!!

My tupleArray:

[(key: 1, value: "A"), (key: 2, value: "V"), (key: 3, value: "E"), (key: 4, value: "N")]

What I would like the output to be:

[(key: 1, value: "A"), (key: 4, value: "V"), (key: 5, value: "E"), (key: 6, value: "N")]

What the current output is:

[(key: 1, value: "A"), (key: 5, value: "E"), (key: 6, value: "N")]

Code:

var tupleArray = [(key: Int, value: String)]()
var row = 1
var newValues = 2


let filterTupleArray = self.tupleArray.filter { $0.key > row}

filterTupleArray.forEach { (data) in
    let newKey = data.key + newValues
    let values = data.value
    self.tupleArray = self.tupleArray.filter({ $0.key != data.key})
    self.tupleArray.append((key: newKey, value: values))
}

Upvotes: 0

Views: 133

Answers (2)

Lioz Balki
Lioz Balki

Reputation: 55

hii you can do this in two ways

one with dict:[Int : String]

and one with array

if you got this var dict:[Int : String] = [1: "A" , 2: "V" ,3: "E" ,4: "N"]

jest do

//for dict way:

var newDict:[Int :  String] = [:]

//for array way:

var tupleArray = [(key: Int, value: String)]()

the code:

   for item in arr {
        var old = dict[item] ?? ""
        var i = item
        i += 2

        if item != 1 {
        newDict.updateValue(old, forKey: i)
            tupleArray.append((key: i, value: old))
        }else{
        newDict.updateValue(old, forKey: 1)
            tupleArray.append((key: 1, value: old))
        }

i hope its be helpful :)

Upvotes: 1

Martin R
Martin R

Reputation: 539915

You can map each tuple in the array to a new tuple with the same or a modified key:

tupleArray = tupleArray.map {
    (key: $0.key > row ? $0.key + newValues : $0.key, value: $0.value)
}

Self-contained example:

var tupleArray = [(key: 1, value: "A"), (key: 2, value: "V"),
                  (key: 3, value: "E"), (key: 4, value: "N")]

let row = 1
let newValues = 2

tupleArray = tupleArray.map {
    (key: $0.key > row ? $0.key + newValues : $0.key, value: $0.value)
}

print(tupleArray)
// [(key: 1, value: "A"), (key: 4, value: "V"), (key: 5, value: "E"), (key: 6, value: "N")]

Upvotes: 3

Related Questions