So I was writing code to differentiate multiple versions of my app:
static var jsonURLNL = {
if ProcessInfo.processInfo.environment["CONSUMER"] != nil {
return URL(string: "consumerURL")!
}
return URL(string: "professionalURL")!
}()
But I got a compiler error:
Unable to infer complex closure return type; add explicit type to disambiguate
Why can't the Swift compiler know that this will return a URL
? I think it is fairly obvious in this case.
My goal with this question is not to give critique on Xcode or Swift, it is to increase my knowledge of how the compiler infers types in Swift.
Best Answer
The return type of a closure is only inferred automatically if the closure consists of a single expression, for example:
or if the type can be inferred from the calling context:
or
Simplified examples: This single-expression closure compiles:
but this multi-expression closure doesn't:
The following lines compile because the type is inferred from the context:
See also the quote from Jordan Rose in this mailing list discussion:
and the SR-1570 bug report.
(Both links and the quote are copied from How flatMap API contract transforms Optional input to Non Optional result?).