Swift array array with a specific format

For an array containing these elements:

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

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

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

result:

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

I used zip(array, array.indices)instead array.enumerated()because you specifically asked for a tuple with an array index - enumerated()created tuples with zero integer offsets. If your source collection is an array, that doesn't matter, but other collections (like ArraySlice) will behave differently.

+9
source

Source: https://habr.com/ru/post/1691040/


All Articles