如何快速获取二维数组中的第一维

时间:2018-07-14 07:56:31

标签: arrays swift

如何快速获取二维数组中的第一维,我的意思是这样的: 这是带有字符串类型的二维数组:

[["1","2"],["4","5"],["8","9"]]

我想要的是这样的数组:

["1","4","8"]

1 个答案:

答案 0 :(得分:2)

您可以在最外层数组的first instance property调用中,在每个子数组上调用compactMap(_:)

let arr = [["1", "2"], ["4", "5"], ["8", "9"]]
let firstElements = arr.compactMap { $0.first } // ["1", "4", "8"]

但是请注意,firstOptional属性,对于空集合是nil,并且nil会导致compactMap(_:)调用的转换将被删除。例如:

let arr = [["1", "2"], [], ["8", "9"]]
let firstElements = arr.compactMap { $0.first } // ["1", "8"]

在一般情况下,访问每个子数组中的 n 索引,您可以将非可选的subscript(_:)访问器用作map(_:)调用的一部分在最外层的数组上,但是要特别注意,尝试访问不存在的元素(索引超出范围)将导致运行时异常。

let arr = [["1", "2"], ["4", "5"], ["8", "9"]]
let idx = 1

// proceed only if idx is a valid index for all sub-arrays
if idx >= 0 && (!arr.contains { idx >= $0.count }) {
    let subElements = arr.map { $0[idx] } // ["2", "5", "9"]
    // ...
}
else {
    // this would correspond to an index that is invalid in at
    // at least one of the sub-arrays.
}

或者,您可以简单地过滤掉与索引超出范围相对应的子数组下标访问,例如使用compactMap(_:)

let arr = [["1", "2", "3"], ["4", "5"], ["8", "9", "10"]]
let idx = 2
let subElements = arr
    .compactMap { 0..<$0.count ~= idx ? $0[idx] : nil } // ["3", "10"]