[SR-2911] Casting through options has bugs and misleading warning #45505
Labels
bug
A deviation from expected or documented behavior. Also: expected but undesirable behavior.
compiler
The Swift compiler in itself
type checker
Area → compiler: Semantic analysis
Additional Detail from JIRA
md5: 3525a407b4ca643437db033ecbad447d
Issue Description:
Normally in guard and if condition lists, you look up a value in a dictionary and conditionally cast:
if let value = dict[key] as? T, ...
The "as?" operator passes the Any? type through, and the lhs result is T, not T?. However, this doesn't happen when you conditionally cast T? to U, for example, when a dictionary is [AnyHashable: String]:
guard let value = dict["Key"] as? NSString
else { fatalError() }
See error shown here http://i.imgur.com/SkXkk6o.jpg
In this case, the compiler asserts that a cast from String? to an unrelated type NSString always fails. You can mitigate this by sticking an "Any" cast in the middle:
guard let value = dict["Key"] as Any as? NSString
else { fatalError() }
Joe Groff: "This is a bug. 'String as NSString' works, and you can cast through Optionals 'T? as? U', so transitively this also works, despite the misleading warning. Please file a bug report if you haven't yet."
The text was updated successfully, but these errors were encountered: