为什么 Swift 打印只有一个 for 循环的多维数组



我在 Swift 中有以下代码:

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

为什么 Swift 打印一个带有 1 for 循环的多维数组。我怎么能行和列,如果我没有第二个 for 循环?

因为您正在为每次迭代打印数组,所以在您的情况下 array[x] 本身就是一个数组

它与print([6,8,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 

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]]]]

X 递增,直到 array.count

数组

是包含数组的数组。因此,它打印了第 1 行,然后是第 2 行、第 3 行。

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

最新更新