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
  print(elem)
  return elem
}

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

b = a.flatMap { (elem: [Int]) -> [Int] in
  print(elem)
  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 :)

-- 
Ross
_______________________________________________
swift-dev mailing list
swift-dev@swift.org
https://lists.swift.org/mailman/listinfo/swift-dev

Reply via email to