[swift-users] [swift-evolution] Conditional casting and conditional binding: Wierd edge case or flawed design

Erica Sadun erica at ericasadun.com
Mon Oct 10 16:09:01 CDT 2016


> On Oct 10, 2016, at 11:08 AM, Joe Groff <jgroff at apple.com> wrote:
> 
> 
>> On Oct 9, 2016, at 1:10 PM, Erica Sadun via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>> 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?.
>> 
>> * dict[key] returns Any?
>> * Any? as T returns T?, not T??
>> * the conditional binding binds T? to T
>> * PROFIT!
>> 
>> However, this (somewhat illogical) "sugar" 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 http://i.imgur.com/SkXkk6o.jpg <http://i.imgur.com/SkXkk6o.jpg>)
>> 
>> * dict[key] returns String?
>> * String? as T is guaranteed to fail
>> 
>> 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() }
>> 
>> If that's not "magic", I don't know what is.  (You can also cast the dictionary to [AnyHashable: NSString], etc.)
> 
> 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.
> 
> -Joe
> 

https://bugs.swift.org/browse/SR-2911 <https://bugs.swift.org/browse/SR-2911>

(changed lists to reply on Swift-Users)

-- E

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161010/b600f153/attachment.html>


More information about the swift-users mailing list