convert list of list to list in swift

To convert a list of lists to a single list in Swift, you can use the flatMap method on the nested arrays. Here's an example:

main.swift
let list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let singleList = list.flatMap { $0 }
print(singleList) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
131 chars
4 lines

In this code, we first define our list of lists as list. We then use the flatMap method on list, which takes a closure that operates on each element of list. The closure { $0 } simply returns each element of the array that it receives.

The result of flatMap is a flattened array with all of the elements of the nested arrays concatenated into a single list. We store this result in singleList and then print it to the console.

By using flatMap, we can easily convert a nested array structure into a single flat list.

gistlibby LogSnag