Skip to content

Instantly share code, notes, and snippets.

@iamjono
Last active April 4, 2019 15:08
Show Gist options
  • Save iamjono/3c55a264fb9760d75223fdd6bb37b669 to your computer and use it in GitHub Desktop.
Save iamjono/3c55a264fb9760d75223fdd6bb37b669 to your computer and use it in GitHub Desktop.
Flattens a nested array of integers to [Int]
/**
* Flatten
* A function designed to recursively flatten nested array of integers to a single array of integers
* - parameter: a single element of type [Any]
* - returns: an array of integers [Int]
*/
func flatten(_ a: [Any]) -> [Int] {
// Initialize the internal storage array
var container = [Int]()
// Iterate through the input
a.forEach{
e in
// If element is an integer append and continue
if let elem = e as? Int {
container.append(elem)
// If element is a nested array, invoke function recursively
} else if let isArray = e as? [Any] {
container += flatten(isArray)
}
}
// return flattened array component
return container
}
// Test with full nested integer example
let arr1 : [Any] = [[1,2,[3]],4]
print(flatten(arr1))
// -> [1, 2, 3, 4]
// test with one of the integers typed as a string
let arr2 : [Any] = [["1",2,[3]],4]
print(flatten(arr2))
// -> [2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment