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]]]
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:
let array = [[1, 2], [3, 4]]
let newArray = array.map { inner in
return [inner, [5, 6]]
}
Less verbose but more compact version: (thanks to Honey)
let newArray = array.map { [$0, [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] {
..
}
}
[[[1, 2], [5, 6]], [[3, 4], [5, 6]]] in my playground.let newArray = array.map { [$0, [5,6]]} where $0 is an element of array, ie its first element is [1,2] then its second is [3,4]. You don't need to write inner in because the compiler is smart enough to know there is a parameter and also doesn't care of its name. if there were two parameters then you would have $0 & $1. Also the closure is smart enough to know that you are returning something so you also don't need to specify that. Swift is super swift!