flatMap can't be compiled while using "return" keyword in closure

Code below works.

var numbers = [Set([1,2,3]), Set([4,5,6]), [], Set()]
var numList = numbers.flatMap { $0 }

However, when I change the above code to return a value in the closure of flatMap. Like this,

var numbers = [Set([1,2,3]), Set([4,5,6]), [], Set()]
var numList2 = numbers.flatMap {
    let n = $0
    return n
}

It's can't be compiled and shows errors. It gives me the suggestion even though I am returning a non-optional type.

'flatMap' has been renamed to 'compactMap(:)': Please use compactMap(:) for the case where closure returns an optional value

Swift is able to infer the return type of a closure only if it contains a single expression.

The closure:

{
    let n = $0
    return n
}

contains 2 statements, so Swift needs a little help to understand its type. In order to make it compile, you can write the type of the closure explicitly:

var numbers = [Set([1,2,3]), Set([4,5,6]), [], Set()]
var numList2 = numbers.flatMap { x -> Set<Int> in
    let n = x
    return n
}

This will improve once SE-326 is released.

1 Like