Skip to content

Compiler's wrong code interpretation causes loop of error messages #67720

Open
@sjvolkmann

Description

@sjvolkmann

This is how it looks like in latest Xcode 15.0 beta 5:

Screenshot 2023-07-28 at 05 35 45

And this is the code that causes this error:

@State private var version: String = "Sample App" + Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String

This will Xcode let show an error and a warning which both say the exact opposite: "Insert ' as! String'" and "Remove 'as! String'". The solution is easy as follows.

@State private var version: String = "Sample App" + (Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String)

The problem is that there needs a cast to String first for the Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString" before joining the two. However, the compiler does understand the code as it would be like this:

@State private var version: String = ("Sample App" + Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")) as! String

This does explain the error and the warning, the error because the cast is still required for the latter and the warning because the code inside the brackets is already a String.

I don't know if this is an issue that would be worth its effort because it goes much into detail. However, I do think this is a very common because fundamental error message. As of now the error and warning together doesn't make much sense.

Metadata

Metadata

Labels

bridgingFeature → casting: type bridgingbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.castingFeature: explicit casting (is, as, as? and as!)diagnostics QoIBug: Diagnostics Quality of Implementationfix-itsFeature: diagnostic fix-itsswift 5.8type checkerArea → compiler: Semantic analysis

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions