[swift-users] Why does casting to Any make my forced downcast not crash?

Joe Groff jgroff at apple.com
Tue Mar 14 13:50:55 CDT 2017


> On Mar 13, 2017, at 5:13 AM, Kim Burgestrand via swift-users <swift-users at swift.org> wrote:
> 
> Here are two implementations that I'd expect to be equivalent, but something's different because the first example crashes, whereas the second example does not crash.
> 
> What's the difference between these two? Why does casting to Any before the forced downcast to T have any effect?

It shouldn't. Please file a bug, if you haven't already.

-Joe

> Example 1: (`unexpectedly found nil while unwrapping an Optional value`)
> ```
> func cast<T>(_ name: String?) -> T {
>     return name as! T
> }
> 
> debugPrint((cast(nil) as String?) as Any))
> ```
> 
> Example 2: (prints `nil`)
> ```
> func cast<T>(_ name: String?) -> T {
> return (name as Any) as! T
> }
> 
> 
> debugPrint((cast(nil) as String?) as Any)
> ```
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list