Description
Description
I'm finding it hard to describe this one, but when you iterate over a literal array with forEach
and there is an error in the closure, the Swift compiler might show a cannot convert value of type 'Any'
for the closure argument instead of the actual error, if that value is used before the error happens. It's probably best to just show an example.
Steps to reproduce
The swift compiler will throw an error on this code because we are trying to access a method that doesn't exist, but instead of saying that, the compiler shows a different type conversion error.
// Wrong
[true, false].forEach { value in
_ = value ? "yes" : "no"
// ^~~~~ error: cannot convert value of type 'Any' to expected condition type 'Bool'
1.nonexistentMethod
}
If you change the order of lines, it shows the correct message:
// Correct
[true, false].forEach { value in
1.nonexistentMethod
// ^~~~~~~~~~~~~~~~~ error: value of type 'Int' has no member 'nonexistentMethod'
_ = value ? "yes" : "no"
}
Or, if you remove the code that triggers the actual error, the whole closure compiles without a type conversion error:
// No error
[true, false].forEach { value in
_ = value ? "yes" : "no"
}
This only seems to happen for literal arrays. If you put the values in a variable and call forEach
on that, it works as expected:
// Correct
let options = [true, false]
options.forEach { value in
_ = value ? "yes" : "no"
1.nonexistentMethod
// ^~~~~~~~~~~~~~~~~ error: value of type 'Int' has no member 'nonexistentMethod'
}
Environment
- Swift compiler version info
swift-driver version: 1.75.2 Apple Swift version 5.8 (swiftlang-5.8.0.124.2 clang-1403.0.22.11.100) Target: arm64-apple-macosx13.0
- Xcode version info
Xcode 14.3 Build version 14E222b
- Deployment target: N/A