Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Swift array with specific format

Tags:

arrays

swift

Given an array that contains elements like this:

let array = [[a], [b, c], [d, e, f]]

Is there an elegant way to convert this array to an array which returns a tuple with the index of the outer array:

let result = [(a, 0), (b, 1), (c, 1), (d, 2), (e, 2), (f, 2)]
like image 446
Zigii Wong Avatar asked Jan 04 '23 01:01

Zigii Wong


1 Answers

let array = [["a"], ["b", "c"], ["d", "e", "f"]]
let result = zip(array, array.indices).flatMap { subarray, index in
    subarray.map { ($0, index) }
}

result is:

[("a", 0), ("b", 1), ("c", 1), ("d", 2), ("e", 2), ("f", 2)]

I used zip(array, array.indices) instead of array.enumerated() because you specifically asked for a tuple with the array indexenumerated() produces tuples with zero-based integer offsets. If your source collection is an array, it doesn't make a difference, but other collections (like ArraySlice) would behave differently.

like image 198
Ole Begemann Avatar answered Jan 05 '23 15:01

Ole Begemann