快速将新列追加到数组

时间:2019-07-10 18:52:06

标签: arrays swift multidimensional-array append

我想按行组织多维数组。 我有一个从一个主数组创建3个数组的函数。我想以理想的列形式将这些子数组添加到新数组中。

我尝试了以下操作:

/* Note

-subArray is a data structure where i have 3 values stored at each 
index index. these are named data1, data2, data3. I'm accessing them 
with the line chamberOne.append(thing.data1). this is referenced 
from tempCount's data. 

- data structure: 
at index # 1
 -data1
 -data1
 -data3

*/


static func subArray()->[String]
{
   var temp = mainArray[0...11]
   let tempCount = Array(temp)
   var returnArr: [String] = []

   var chamberOne: [String] = []
   for thing in tempCount
   {
      chamberOne.append(thing.data1)
   }
   // i have 2 more functions built the same as chamberOne, but they 
   //are named chamberTwo and chamberThree

   //as of right now I am appending like this
   returnArr + chamberOne + chamberTwo + chamberThree
  // this brings all the data into a single dimension array. 
}

我想要一种将chamberOnechamberTwochamberThree附加为列或行的方法,也可以,我只想通过附加某种形式的组织到多维空间中一维数组(chamberOne)到多维数组(returnArr)。

2 个答案:

答案 0 :(得分:0)

让我们假设您有两个数组,例如:

1
4
6
7
2

1
4
6
7
2

现在,我们创建一个将容纳其他数组的数组,例如:

var arr1 = ["a", "b", "c"]
var arr2 = ["1", "2", "3"]

我们现在可以将两个数组都添加到var multiDimArray = [[String]]() //Array of subarrays

multiDimArray

如果我们打印multiDimArray.append(arr1) multiDimArray.append(arr2) ,我们将得到multiDimArray

如果我们需要第一个“行”,我们可以使用[["a", "b", "c"], ["1", "2", "3"]]来获得它,而multiDimArray[0]

答案 1 :(得分:0)

如果我正确理解了您的问题,则需要[[String]]Array of Arrays of String。我将按照以下方法修改您的功能来解决该问题:

static func subArray() -> [[String]]
{
   var temp = mainArray[0...11]
   let tempCount = Array(temp)
   var returnArr: [[String]] = []

   var chamberOne: [String] = []

   for thing in tempCount
   {
      chamberOne.append(thing.data1)
   }

   returnArr.append(chamberOne)

   //Initialise chamberTwo and chamberThree here. Then append to the 2D array.
   returnArr.append(chamberTwo)
   returnArr.append(chamberThree)

   //The returnArr now looks like this [chamberOne, chamberTwo, chamberThree]
   returnArr
}