Multi-dimensional Arrays

computer_key_InsertModifying values of elements:

vCR[1].insert(0,atIndex: 1)        // vCR[1] equals [1,0,2]
vCR.insert([34,44,54],atIndex: 2)

vCR now equals [[1],[1,0,2],[34,44,54],[3,4,5,8,9],[100,200]]. The single-dimensional array [34,44,54] has been inserted into row 3, moving all the other rows along one.

vCR[1...2] = [[55,56,57],[65,66],[75,76,77]]

The 2nd through to the 3rd rows of vCR are replaced with the rows shown above. Note that the number of rows being replaced does not need to equal the number of rows being added. vCR now equals [[1],[55,56,57],[65,66],[75,76,77],[3,4,5,8,9],[100,200]].

vCR[2][1...1] = [67,68,69]

The 2nd element of the 3rd row of vCR — ‘[66]’ — is replaced with [67,68,69]. vCR now equals [[1],[55,56,57],[65,67,68,69],[75,76,77],[3,4,5,8,9],[100,200]].

let removedItem = vCR[1].removeAtIndex(1)   // vCR[1] equals [55,57]

vCR now equals [[1],[55,57],[65,67,68,69],[75,76,77],[3,4,5,8,9],[100,200]]..

let removedArray = vCR.removeAtIndex(4)

removes [3,4,5,8,9] from vCR, the 3rd row of the 2-dimensional array. vCR now equals [[1],[55,57],[65,67,68,69],[75,76,77],[100,200]]..

vCR.removeLast()     // vCR equals [[1],[55,57],[65,67,68,69],[75,76,77]]
vCR[1].removeLast()  // vCR equals [[1],[55],[65,67,68,69],[75,76,77]]
println(board)            // prints [[10,10,10,11],[]]
board.removeAll           // board equals []
println(vCR.reverse())    // prints [[75,76,77],[65,67,68,69],[55],[1]]
println(vCR[3].reverse()) // prints [77,76,75]

strangeloop_stl_oUsing Loops:

for i in 0..<vCR[2].count {
    print("\(vCR[2][i]) ")
}                             // prints 65 67 68 69
for i in vCR[2]
    {print("\(i) ")}          // prints 65 67 68 69
for i in vCR
    { print("\(i) ") }   // prints [1] [55,57] [65,67,68,69] [75,76,77]
for (ndx,no) in enumerate(vCR)
    { println("\(ndx): \(no)") }

The last line, using ‘enumerate’, extracts the index and the value of the element in the array. The output is:
0: [1]
1: [55,57]
2: [65,67,68,69]
3: [75,76,77]

for (index, value) in enumerate(vCR[2]) { println("\(index): \(value)") }

prints:
0: 65
1: 67
2: 68
3: 69

images

Leave a Reply

Your email address will not be published. Required fields are marked *