繁体   English   中英

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

[英]How can get the first dimension in a two-dimensional array in swift

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

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

我想要的是这样的数组:

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

您可以在最外面的数组的compactMap(_:)调用中调用每个子数组的first实例属性

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM