Skip to content

[Diagnostics] Add an educational note explaining closure type inference rules #28572

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions include/swift/AST/EducationalNotes.def
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,7 @@ EDUCATIONAL_NOTES(non_nominal_extension, "nominal-types.md")
EDUCATIONAL_NOTES(associated_type_witness_conform_impossible,
"nominal-types.md")

EDUCATIONAL_NOTES(cannot_infer_closure_result_type,
"complex-closure-inference.md")

#undef EDUCATIONAL_NOTES
31 changes: 31 additions & 0 deletions userdocs/diagnostics/complex-closure-inference.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
Inferring Closure Types
---
If a closure contains a single expression, Swift will consider its body in addition to its signature and the surrounding context when performing type inference. For example, in the following code the type of `doubler` is inferred to be `(Int) -> Int` using only its body:
```
let doubler = {
$0 * 2
}
```
If a closure body is not a single expression, it will not be considered when inferring the closure type. This is consistent with how type inference works in other parts of the language, where it proceeds one statement at a time. For example, in the following code an error will be reported because the type of `evenDoubler` cannot be inferred from its surrounding context and no signature was provided:
```
// error: unable to infer complex closure return type; add explicit type to disambiguate
let evenDoubler = { x in
if x.isMultiple(of: 2) {
return x * 2
} else {
return x
}
}
```
This can be fixed by providing additional contextual information:
```
let evenDoubler: (Int) -> Int = { x in
// ...
}
```
Or by giving the closure an explicit signature:
```
let evenDoubler = { (x: Int) -> Int in
// ...
}
```