flatten nested arrays in swift

To flatten a nested array in Swift, you can use a recursive function that iterates through each element of the array and checks if it's an array or not. If it's an array, the function calls itself with the nested array as its argument. If it's not an array, the element is added to the flattened array.

Here is the code:

main.swift
func flattenArray(_ nestedArray: [Any]) -> [Any] {
    var result: [Any] = []
    
    for element in nestedArray {
        if let subArray = element as? [Any] {
            result += flattenArray(subArray)
        } else {
            result.append(element)
        }
    }
    
    return result
}
300 chars
14 lines

This function takes an array of type [Any], which means it can handle any type of nested array. It returns an array of type [Any], which contains all the elements of the flattened array.

You can call this function like this:

main.swift
let nestedArray = [1, 2, [3, 4, [5, 6]], 7, [8]]
let flattenedArray = flattenArray(nestedArray)
print(flattenedArray) // [1, 2, 3, 4, 5, 6, 7, 8]
146 chars
4 lines

This will print out the flattened array, which contains all the elements of the nested array.

gistlibby LogSnag