Missing conditional cast fix-it?

Just highlighting an issue:

https://bugs.swift.org/browse/SR-13899

let any: Any = 1
if let int = any as Int {
  // ...
}
$ swiftc missing-checked-cast-fixit.swift
missing-conditional-cast-fixit.swift:2:18: error: 'Any' is not convertible to 'Int'; did you mean to use 'as!' to force downcast?
if let int = any as Int {
             ~~~~^~~~~~
                 as!

Would it make sense to also have:

missing-checked-cast-fixit.swift:2:18: error: 'Any' is not convertible to 'Int'; did you mean to use 'as?' to conditionally downcast?
if let int = any as Int {
             ~~~~^~~~~~
                 as?

I ran into a case where the latter use case would've been helpful. Supporting it seems like a potential starter task. Any thoughts?

I would say that for this case in specific only the latter would make sense since conditional binding expects an optional type.
This could be instead of presenting two error diagnostics we should present the error diagnostics only as 'Any' is not convertible to 'Int' and attach the fix-its to two notes and where it makes sense e.g. this conditional binding, only present the as? note with the proper fix-it

1 Like

This sounds nice! Just like the optional unwrapping diagnostics:

// optional-unwrapping.swift
let optional: Int? = 1
let int: Int = optional
$ swift optional-unwrapping.swift
optional-unwrapping.swift:2:16: error: value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let int: Int = optional
               ^
optional-unwrapping.swift:2:16: note: coalesce using '??' to provide a default when the optional value contains 'nil'
let int: Int = optional
               ^
                        ?? <#default value#>
optional-unwrapping.swift:2:16: note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
let int: Int = optional
               ^
                       !
1 Like

Yeah :)
But thinking better about it maybe we would have to be careful when suggesting as? fix-it because it may not make sense in certain situations like:

let a: Any = 1
let _: Int = a as Int // suggesting as? here wouldn't be correct 
let _: Int? = a as Int // here would be fine I think so would be `as!`

Maybe the most likely situation where suggesting as? would be good is on the conditional binding...
But in any case, maybe separate the diagnostics and note would still be a good thing

1 Like

Great point! Smarter (more context-sensitive) diagnostics sound good.

1 Like