0

I have a structure like [[[ ]]] which I want to convert to [].

E.g. [ [ [ "Hi" ] ] ] into [ "Hi" ]

How can I do this in Swift?

4
  • Your question is unclear after your edit. What is [ [ [ params: CVarArg... ] ] ]? What exactly are you trying to achieve? Commented Feb 24, 2017 at 6:36
  • Is this a follow-up on your previous question stackoverflow.com/q/42428504/1187415? If yes, then you should say so. Commented Feb 24, 2017 at 6:38
  • it is the same question. just wanted to make explicit that argument type is CVarArg. at the end i am trying to do this - return NSString(format: content, arguments: getVaList(params)). But problem is my params is coming as [[[ ]]] and i want to convert it to [] Commented Feb 24, 2017 at 6:43
  • I have answered your other question stackoverflow.com/q/42428504/1187415, but that one has nothing to do with converting nested arrays, only with passing variable argument lists. – I have therefore reverted this question to the initial version. Commented Feb 24, 2017 at 8:04

4 Answers 4

6

joined() returns (a lazy view of) the elements of an collection, concatenated. This can be applied repeatedly for deeper nested collections:

let arr = [ [ [ "A", "B" ], ["C"] ], [ [ "D", "E" ], ["F"] ] ]

let flattened = Array(arr.joined().joined())
print(flattened) // ["A", "B", "C", "D", "E", "F"]

The outer Array() constructor builds an array from the sequence. Apart from that, no intermediate arrays are created.

If you just want to iterate over the nested array then the joined sequence is sufficient:

for elem in arr.joined().joined() {
    print(elem)
}
Sign up to request clarification or add additional context in comments.

Comments

3

This is exactly what flatMap() does:

let arr = [ [ [ "A", "B" ], ["C"] ], [ [ "D", "E" ], ["F"] ] ]

// each call reduces the array by one dimension

let flattened = arr.flatMap{$0}.flatMap{$0}

// returns ["A", "B", "C", "D", "E", "F"]

Comments

1

Use reduce(_:_:) with your array this way.

let array = [[["One","Two","Three"],["Four","Five"]],[["Six"]]]
let newArray = array.reduce([]) { $0 + $1.reduce([]){ $0 + $1 } }
print(newArray) //["One", "Two", "Three", "Four", "Five", "Six"]

Comments

0

you can use join as

let numbers = [[1,2,3],[4],[5,6,7,8,9]]
let newArray = Array(numbers.joined().joined())
print(newArray)//[1,2,3,4,5,6,7,8,9]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.