简体   繁体   English

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

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

How can get the first dimension in a two-dimensional array in swift,what I mean is like this: Here is a two-dimensional array with the type of string: 如何快速获取二维数组中的第一维,我的意思是这样的:这是一个具有字符串类型的二维数组:

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

what I want is array like this: 我想要的是这样的数组:

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

You can invoke the first instance property on each sub-array as part of a compactMap(_:) invocation of the outermost array. 您可以在最外面的数组的compactMap(_:)调用中调用每个子数组的first实例属性

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

Note however that first is an Optional property, that is nil for empty collections, and that a nil result in transform of the compactMap(_:) invocation will be removed. 但是请注意, firstOptional属性,对于空集合为nil ,并且将删除compactMap(_:)调用转换中的nil结果。 Eg: 例如:

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

For the general case, accessing the nth index in each sub-array, you can make use of the non-optional subscript(_:) accessor as part of a map(_:) invocation on the outermost array, carefully noting however that an attempt to access a non-existing element ( index out of bounds ) will lead to a run-time exception. 在一般情况下,访问每个子数组中的第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.
}

Alternatively, you could simply filter out sub-array subscript accesses that would correspond to index out of bounds, eg using compactMap(_:) : 或者,您可以简单地过滤出与索引超出范围相对应的子数组下标访问,例如使用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