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}
2
  • 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 Commented Aug 16, 2018 at 20:18
  • 1
    This solved my question, sorry for posting duplicate post Commented Aug 16, 2018 at 21:21

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.