0

I have an array that takes in a set of values. At a certain index in the array, the value is an array. So it looks like this

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

I'm trying to change the array value to be like this

[1, 2, 3, 4, 5]

How would you go back about doing this in Swift?

Here is how I get the result

let array = [value1, value2, [value3, value4]].compactMap{$0}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • What have you tried and what where the results? Show any code you have tried and what part you are having an issues with. [SO new-array-from-index-range-swift](https://stackoverflow.com/questions/24034398/new-array-from-index-range-swift) – MwcsMac Aug 16 '18 at 20:18
  • 1
    This solved my question, sorry for posting duplicate post – Simon Mcneil Aug 16 '18 at 21:21

1 Answers1

0

Here is a straightforward solution that handles int values and arrays of ints in the original array

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
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52