2016-03-04 46 views
0

我在夫特以下代碼:爲什麼夫特打印多維數組只用一個for循環

var array: [[Int]] = [[6,8,1], 
         [3,3,3], 
         [2,1,2]]; 

for (var x=0;x<array.count;x++){ 
     print (array[x]); 
    } 
} 

結果是:

6,8,1 
3,3,3 
2,1,2 

爲什麼夫特打印多維數組1 for循環。以及如何我可以 行和列,如果我沒有第二個循環?

+0

請添加更多的投入到你的問題。你的問題不清楚 – UIResponder

+0

它只是打印第一個數組內的元素 – Lee

+0

預期的輸出是什麼,只打印每個數字? – Moritz

回答

1

因爲要打印爲每次迭代陣列,你的情況陣列[X]陣列本身

它是一樣print([6,8,1])

0

X被遞增直到array.count你的數組是包含數組的數組。因此它打印第一,然後是第二,第三行。

+0

我如何才能像矩陣訪問元素的行和列,而我迭代數組? –

1

你有

for var i = 0 ; i < array.count; i++ { 
    for var j = 0; j < array[i].count; j++ { 
     print(array[i][j]) 
     } 
} 
i - Row 
j - Column 
0
var store: [[Int]] = [ 
    [6, 8, 1], 
    [3, 3, 3], 
    [2, 1, 2, 4], 
    [] 
] 
// returns optional value, if you pass wrong indexes, returns nil 
func getValue<T>(store:[[T]], row: Int, column: Int)->T? { 
    // check valid indexes 
    guard row >= 0 && column >= 0 else { return nil } 
    guard row < store.count else { return nil } 
    guard column < store[row].count else { return nil } 

    return store[row][column] 
} 

let v31 = getValue(store, row: 3, column: 0) // nil 
let v21 = getValue(store, row: 2, column: 1) // 1 
let v01 = getValue(store, row: 0, column: 1) // 8 
let v23 = getValue(store, row: 2, column: 3) // 4 

let store2 = [["a","b"],["c","d"]] 
let u11 = getValue(store2, row: 1, column: 1) 

let store3:[[Any]] = [[1, 2, "a"],[1.1, 2.2, 3.3]] 
let x02 = getValue(store3, row: 0, column: 2) // "a" 
let x11 = getValue(store3, row: 1, column: 1) // 2.2 
1

Array型採用所使用的print功能CustomStringConvertible協議來訪問它的每一行和每一列。該實現是這樣的,它列出了數組中用逗號分隔的所有元素。對於數組中的每個元素,將使用相同協議的實現。這就是爲什麼你可以打印你的方式做,實際上你甚至可以打印只是array,並且比更:

let array1 = [0, 1] 
let array2 = [array1, array1] 
let array3 = [array2, array2] 
let array4 = [array3, array3] 

print(array1) // [0, 1] 
print(array2) // [[0, 1], [0, 1]] 
print(array3) // [[[0, 1], [0, 1]], [[0, 1], [0, 1]]] 
print(array4) // [[[[0, 1], [0, 1]], [[0, 1], [0, 1]]], [[[0, 1], [0, 1]], [[0, 1], [0, 1]]]]