Jordan Smith
Jordan Smith

Reputation: 10378

Swift: how do I concatenate a [[String]] to a [String] the right way?

There are new Array functions in swift - map, reduce etc.

I'd like to use these to concatenate a [[String]] to a [String] but I can't figure out how. (I'm assuming map or reduce would do what I want but could be wrong).

What is the best way to do what I need to?

Upvotes: 2

Views: 1131

Answers (1)

Nate Cook
Nate Cook

Reputation: 93276

You'll want to use reduce for that, since you're basically going from an array of T down to T, it's just that T = [String].

let stringArray = stringArrayArray.reduce([]) { $0 + $1 }

You can write it even more concisely by using operator shorthand instead of a closure:

let stringArray = stringArrayArray.reduce([], +)

And here's the full way to write it out, so you can see what's happening:

1: let stringArray = stringArrayArray.reduce([]) {
2:         (accumulated: [String], element: [String]) -> [String] in
3:         return accumulated + element
4:     }

In line 1, we provide an empty array for the initial value. Line 2 defines the arguments and return type of the closure: accumulated is the initial value in the first iteration, and the result of the previous iteration thereafter, while element is the current element of the source array. Line 3 simply adds the accumulated array with the current element to merge them together.

Upvotes: 4

Related Questions