如何在 Swift 3.0 中将动态大小的二维数组填充为 X x 4 二维数组?



我想在 Swift 3.0 中编写一个函数,它将填充字符串数组的 2D 数组,意思是类似于 {{"Mr."、"John"、"Q."、"Public"} {"Ms."、"Jane"、"E."、"Doe"}...}

在我的程序中,标题和名字一样,都在自己的数组中,而中间名首字母和姓氏一起在自己的数组中。

到目前为止,我有:

func build2DStringArray() -> [[String]]{
var col = 0
var row = 0
var string2DArray = [[String]]()
for title in titles{
string2DArray[col][row].append(title){
for firstname in firstNames{
string2DArray[col][row].append(firstname){
for lasttwo in lastTwo{
string2DArray[col][row].append(middleinit)
string2DArray[col][row].append(lastname)
col += 1
row += 1
}
}
}
}
}
return string2DArray
}

但是当我运行它时,我得到"索引超出范围"。我怎样才能让它做我需要的事情。截至目前,我需要有 150 组 4 个字符串,尽管我无法对这些数字进行硬编码。我尝试查找文档,对于这种事情来说它非常糟糕。因此,我为什么来这里。

一个问题是您正在初始化[[String]],但您还需要为每一列append一个[String]。另一个问题是,如果其中一个数组比其他数组长,会发生什么情况?

这是一种使用任意数量的[String]执行此操作的方法:

func zipIntoArray<T>(arrays: [T]...) -> [[T]] {
var result = [[T]]()
var index = 0
while true {
var current = [T]()
for array in arrays {
guard array.indices.contains(index) else { return result }
current.append(array[index])
}
result.append(current)
index += 1
}
}
let a = ["one a", "two a", "three a", "four a"]
let b = ["one b", "two b", "three b"]
let c = ["one c", "two c", "three c"]
let d = ["one d", "two d", "three d"]
let big = zipIntoArray(arrays: a, b, c, d)
print(big)
// [["one a", "one b", "one c", "one d"], ["two a", "two b", "two c", "two d"], ["three a", "three b", "three c", "three d"]]
print(big[0][1])
// two b

当函数遇到任何数组的末尾时,它会立即返回。这样,每行都有相同数量的元素。

这不会遵循您对"[col][row]"的称呼,而是用作"[row][col]",但我觉得这是一个小细节,特别是因为后者是许多程序员遵循的范式。行往往是一组关联的数据,因此每个组都包含在单个数组中。更好的可能是取消该数组,而是使用具有命名属性的struct

最新更新