【问题标题】:Trying to make a specific index in my array to no longer be of array type [duplicate]试图使我的数组中的特定索引不再是数组类型[重复]
【发布时间】:2019-01-23 20:34:34
【问题描述】:

我有一个接受一组值的数组。在数组中的某个索引处,该值是一个数组。所以它看起来像这样

[1, 2, 3, [4, 5]]

我正在尝试将数组值更改为这样

[1, 2, 3, 4, 5]

你会如何回过头来在 Swift 中做这件事?

这是我得到结果的方式

let array = [value1, value2, [value3, value4]].compactMap{$0}

【问题讨论】:

  • 你尝试过什么,结果在哪里?显示您尝试过的任何代码以及您遇到问题的部分。 SO new-array-from-index-range-swift
  • 这解决了我的问题,抱歉发布重复帖子

标签: arrays swift filter reduce


【解决方案1】:

这是一个简单的解决方案,可以处理原始数组中的 int 值和 int 数组

let arr:[Any] = [1, 2, 3, [4, 5]]

var output: [Int] = []

for x in arr {
    if let value = x as? Int {
        output.append(value)
    } else if let array = x as? [Int] {
        output.append(contentsOf: array)
    }
    //else ignore
}

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 2018-11-22
    • 2018-11-29
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多