Skip to content

Instantly share code, notes, and snippets.

@mehdi-S
Last active April 8, 2018 17:26
Show Gist options
  • Save mehdi-S/ddc5d4dcccae87cad543f1e0b56e4b5a to your computer and use it in GitHub Desktop.
Save mehdi-S/ddc5d4dcccae87cad543f1e0b56e4b5a to your computer and use it in GitHub Desktop.
Swift code that flatten nested integer array for job application at citrusByte (you can exec this code and play with value in Xcode Playground)
import Foundation
// nestedArrays will be a sample case to test our function
var nestedArrays = [[1,2,[3,[4,5]]],6] as [Any]
func flattenArray(nestedArrays array: [Any]) -> [Int]{
var newArray = [Int]()
array.forEach { item in
// recursively check is array item is an array, if so, pass it to flattenArray func
if let arrayItem = item as? [Any] {
// I love Swift for the power of the if-let statement
newArray = newArray + flattenArray(nestedArrays: arrayItem)
} else {
newArray.append(item as! Int)
}
}
return newArray
}
let flatArray = flattenArray(nestedArrays: nestedArrays)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment