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

Kim Burgestrand kim at burgestrand.se
Mon Mar 13 07:13:32 CDT 2017


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?

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)
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170313/a06308eb/attachment.html>


More information about the swift-users mailing list