[swift-dev] Type inference of functions with more than one statement

Ross LeBeau ross.lebeau at gmail.com
Fri Jul 8 12:00:21 CDT 2016

It seems that the compiler fails to infer the type of an anonymous function
if the function contains more than one statement. For example, this works:

let a = [[1,2],[3],[4,5,6]]
var b: [Int]
b = a.flatMap { elem in
  return elem

But this fails with an error "cannot convert return expression of type
'[Int]' to return type 'Int?'":

b = a.flatMap { elem in
  return elem

And, of course, if you explicitly type the function, it works again:

b = a.flatMap { (elem: [Int]) -> [Int] in
  return elem

Greg Titus informed me that this is due to a heuristic in the compiler
where it only imports the outer context when type-checking anonymous
functions with a single statement. Before we knew this, I and others, found
it perplexing that out of two functions that return the same value, one
will compile and the other will not.

Are there any plans to extend the context of type-checking in the case of a
failure like this? If not, is it something to consider? It seems like a
difficult problem to solve without rather advanced knowledge of what's
going on.

Also if this has already been brought up, forgive me, I just subscribed to
this list and a quick search of the archives didn't get any hits :)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20160708/49390951/attachment.html>

More information about the swift-dev mailing list