如何在swift中获取二维数组的第一个维度,我的意思是这样的: 这是一个字符串类型的二维数组:
[["1","2"],["4","5"],["8","9"]]
我想要的是这样的数组:
["1","4","8"]
最佳答案
您可以调用 first
instance property在每个子数组上作为 compactMap(_:)
的一部分调用最外层数组。
let arr = [["1", "2"], ["4", "5"], ["8", "9"]]
let firstElements = arr.compactMap { $0.first } // ["1", "4", "8"]
但是请注意,first
是一个可选
属性,即 nil
用于空集合,而 nil
compactMap(_:)
调用的转换结果将被删除。例如:
let arr = [["1", "2"], [], ["8", "9"]]
let firstElements = arr.compactMap { $0.first } // ["1", "8"]
对于一般情况,访问每个子数组中的第 nth 个索引,您可以使用非可选的 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"]
关于arrays - 如何快速获取二维数组中的第一个维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51336504/