-2

I have two arrays given like so...

idArray : [123, 456, 789]

theRowIdArray: ["2", "3", "4"]

Here the theRowIdArray corresponds to the rows of my table in database. And the idArray corresponds to values I have to update in a column in my table against the rows.

How can I merge these two arrays in a format that I can update the rows in my table. I feel this could be achieved using dictionaries..but not sure how...

I wanted something like this...

for (id, rowID) in myDataset { //Here `myDataset` will contain the elements of both arrays
  Update myTable Set theIDColumn = id Where Row_Id = rowID //Here will be code to update DB
}
kfo dof
  • 21
  • 4
  • Does this answer your question? [How can I merge two arrays into a dictionary?](https://stackoverflow.com/questions/32140969/how-can-i-merge-two-arrays-into-a-dictionary) – Joakim Danielson Oct 01 '20 at 10:15

2 Answers2

1

You can use zip(_:_:) method to get a combined array from idArray and theRowIdArray

let combinedArray = Array(zip(idArray, theRowIdArray))

You can not loop over combinedArray like,

for (id, row) in combinedArray {
    print(id, row)
    //add your code here...
}
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • `for (id, rowID) in zip(...` – matt Oct 01 '20 at 09:22
  • If I want to pass `combinedArray ` to a function, what will be its datatype..? The `combinedArray` is being shown like so...`let combinedArray: Zip2Sequence<[Int], [String]>` – kfo dof Oct 01 '20 at 09:31
  • @kfodof Its type will be `[(Int, String)]` and convert `combinedArray` to `Array` type like `Array(zip(idArray, theRowIdArray))`. – PGDev Oct 01 '20 at 09:33
0

You can use a dictionary to combine both arrays like this...

var idArray = [123, 456, 789]
var theRowIdArray = ["2", "3", "4"]

//using Dictionary
var myDataset: [Int : String] = [:]

//combining both array
for (index, element) in idArray.enumerated() {
    myDataset[element] = theRowIdArray[index]
}
print(myDataset) // [123: "2", 456: "3", 789: "4"]

//Loop through your myDataset Dictionary
for (id,rowID) in myDataset {
    print("\(id) = \(rowID)")
     // your code here...
}
2apreety18
  • 181
  • 3
  • 8