arrays - 如何快速获取二维数组中的第一个维度

标签 arrays swift

如何在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/

相关文章:

ios - fatal error : Array index out of range in swift 2

Javascript 数组元素未显示在 div 标签中

java - Java 中整数数组的 Arraylist 的排序和比较

ios - 如何以编程方式设置音频文件的特定顺序?

ios - 无法调用非函数类型的值

ios - 使用代码更改约束常量

ruby - 参数化数组#uniq(即uniq_by)

arrays - 如何使用 swift 中函数的参数将元组值放入字典中

c++ - 在终端中生成一个覆盖先前板的数组

ios - 如何在 Swift 中使用 Alamofire 将正文参数与文件一起传递到多部分文件上传中