iOS Closures in Swift Closure Expressions Closure Expression Shorthand

From shorthand to plain syntax

Hi,

I am having hard time finding the plain syntax of the following shorthand code :

let numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let result = numbers.flatMap({ $0.map( {$0 * 2} ) })
print(result)

Would really much appreciate your help :)

This is is how far I could go :

let numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let result = numbers.flatMap({ (element: [Int]) -> [Int] in
    for number in element {
        let individualResult = number * 2
    }
    return element
})
print(result)

1 Answer

Paolo Scamardella
Paolo Scamardella
24,825 Points

That is because you are returning element inside the flatMap method instead of the individualResult. You are not even using the individualResult at all. You need to add a mutable array before the for in loop, then append the result to the mutable array inside the for in loop, and then return the mutable array after the for in loop.