要获得一行,我可以轻松地进行print(array[3])
。
但是,要获取列,我必须创建一个空数组,遍历所有行,然后追加到数组。对于这么简单的事情来说太过分了!
当前,我必须完成所有这些工作才能获得该专栏:
let array = [[1, 9, 29, 55, 90],
[19, 22, 33, 59, 94],
[33, 44, 55, 62, 101],
[75, 80, 82, 90, 197],
[91, 99, 104, 144, 222]]
func get(column : Int, of array: [[Int]]) -> [Int]? {
guard !array.isEmpty else {
print("array is empty")
return nil
}
guard column < array.count else {
print("such a column doesn't exist")
return nil
}
guard column > -1 else {
print("column index can't be negative")
return nil
}
var column : [Int] = []
for row in 0..<array.count {
column.append(array[row][column])
}
return column
}
get(column: 3, of: array) // Optional([55, 59, 62, 90, 144])