Alek Szczęsnowicz Alek Szczęsnowicz - 8 days ago 5
Swift Question

How to add an array to the member of array in swift 3

for example, we have a swift 3 code piece:

first array

[[1, 2], [3, 4]]
and second
[5, 6]


Which function I should to use to add second at first array like:

[[[1, 2], [5, 6]], [[3, 4], [5, 6]]]

Answer

I don't think you can alter an array in that way because new array's type which is [[Int]] will be different than old one's [Int].

You can use map to do that:

var array = [[1, 2], [3, 4]]

let newArray = array.map { inner in
  return [inner, [5, 6]]
}

If you want to update in-place no matter what, downcast your array to [Any]:

var array: [Any] = [[1, 2], [3, 4]]

for (index, inner) in array.enumerated() {
  array[index] = [inner, [5, 6]]
}

which is not ideal as you have to cast to Int or [Int] every time you want to access integers in the lists:

for inner in array {
  if let inner = inner as? [Int] {
    ..
  }
}
Comments