[swift-users] Compiler can't infer map transfer closure return type?
Jordan Rose
jordan_rose at apple.com
Mon Mar 7 19:15:01 CST 2016
> On Mar 7, 2016, at 15:08, Neil Faiman <neil.swift at faiman.org> wrote:
>
>
>> On Mar 7, 2016, at 4:33 PM, Jordan Rose <jordan_rose at apple.com <mailto:jordan_rose at apple.com>> wrote:
>>
>> Swift very deliberately does not infer types across multiple statements in closure bodies. This is mostly an implementation restriction (our type-checking system can't handle it very well), but it's also a simple rule that explains the implementation restriction, rather than having type inference in closure bodies working some of the time but not all.
>
> OK. I understand the reasoning, and agree that it makes perfect sense. Thanks for the explanation.
>
> That said … I’ll note that Swift already must have logic to infer a single result type from multiple expressions, to wit, the ?: handling logic. In principle, one could collect all the return expressions in a closure and apply the same logic to them. This would have the happy consequence that common trivial cases like “only one return statement” would work as expected.
Multiple expressions and multiple statements aren't the same thing. You'd really want something like this to be inferrable too:
let names = enumValues.map {
switch $0 {
case .Foo:
return ".Foo"
case .Bar:
return ".Bar"
case .Baz
return .Baz
}
}
…but note that I messed up in that last return statement, and now it's not clear what the return type is supposed to be. (Maybe the first two are the mistakes.)
(Okay, so can we collect all the expressions? No, their types may depend on previous lines, which in turn may depend on the types of the arguments, which may also not be inferrable, although in this case they are.)
There are certainly ways to handle more cases than what we handle today, but then we start getting into a weird territory where it's not clear what's handled and what isn't. (Arguably we're already there given how often people ask the question.) Today there's at least a simple rule: if the closure consists of a single expression (or a single return statement), the compiler will look at the body; otherwise it won't.
Best,
Jordan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160307/bac594b3/attachment.html>
More information about the swift-users
mailing list