【问题标题】:Get values from two arrays combined从两个组合的数组中获取值
【发布时间】:2021-01-16 23:56:02
【问题描述】:

我有两个这样的数组...

idArray : [123, 456, 789]

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

这里的theRowIdArray 对应于我在数据库中的表的行。 idArray 对应于我必须在表中的列中针对行更新的值。

如何以可以更新表中行的格式合并这两个数组。我觉得这可以使用字典来实现..但不确定如何...

我想要这样的东西......

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
}

【问题讨论】:

标签: ios swift dictionary


【解决方案1】:

您可以像这样使用字典来组合两个数组...

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...
}

【讨论】:

    【解决方案2】:

    您可以使用zip(_:_:)方法从idArraytheRowIdArray获取组合数组

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

    你不能像combinedArray一样循环,

    for (id, row) in combinedArray {
        print(id, row)
        //add your code here...
    }
    

    【讨论】:

    • for (id, rowID) in zip(...
    • 如果我想将combinedArray 传递给一个函数,它的数据类型是什么......? combinedArray 显示如下...let combinedArray: Zip2Sequence<[Int], [String]>
    • @kfodof 它的类型将为[(Int, String)],并将combinedArray 转换为Array 类型,如Array(zip(idArray, theRowIdArray))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多