Smooth all values ​​of multiple arrays in Swift

I have a dictionary of whole arrays as shown below:

let numbers = [1: [2, 3], 4: [5, 6, 7], 8: [9]]

What I really want is a single flattened array of all values ​​(which themselves are arrays), for example:

[2, 3, 5, 6, 7, 9]

Now I was able to call numbers.values.array to get:

[[2, 3], [5, 6, 7], [9]]

But what I'm looking for is to combine this step further, smooth them.

Does Swift (1.1 or 1.2) use a convenient method for this?

+5
source share
3 answers

Another possible solution is

 [].join(numbers.values) 

And if you want the values ​​in the order corresponding to the sorted dictionary keys, then this will be

 flatMap(sorted(numbers.keys)) { numbers[$0]! } 
+6
source

With a combination of the numbers.values.array and reduce functions, you can simplify this in a single line of code.

 numbers.values.array.reduce([], combine: +) // [5,6,7,2,3,9] 

However, I would like to note that since you are using a dictionary, you cannot guarantee that the values ​​will be sorted, so you can use the sorted function to do this:

 sorted(numbers.values.array.reduce([], combine: +), <) // [2,3,5,6,7,9] 

As @Jeffery Thomas explained, you can also use the flat map that was added in Swift 1.2:

 sorted(numbers.values.array.flatMap { $0 }, <) 

And to take another step using the global sorted function, < is extraneous, since it uses the reduce and flatMap global functions by flatMap , you can delete the array as indicated by Martin R, so it can be reduced to:

 sorted(reduce(numbers.values, [], +)) sorted(flatMap(numbers.values) { $0 }) 
+6
source

This is called flattening , and it is a relatively common operation. There are several ways to do this, so choose the one that suits you.

 numbers.values.array.reduce([], combine: +) // As stated by @Bluehound reduce(numbers.values, [], +) numbers.values.array.flatMap { $0 } // Swift 1.2 (Xcode 6.3) flatMap(numbers.values) { $0 } // Swift 1.2 (Xcode 6.3) 

flatMap may be most useful if the next step after smoothing is mapping.

NOTE. Thanks @MartinR for the syntax tip.

+5
source

All Articles