# Casting from Any to Optional

**URL:** <https://forums.swift.org/t/casting-from-any-to-optional/21883>\
**Category:** Discussion\
**Created:** [March 21, 2019, 3:16pm UTC](https://forums.swift.org/t/casting-from-any-to-optional/21883 "2019-03-21T15:16:33Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![sharplet](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/sharplet/32/6184_2.png) [@sharplet](https://forums.swift.org/u/sharplet)\
**Post date:** [March 21, 2019, 3:30pm UTC](https://forums.swift.org/t/casting-from-any-to-optional/21883/2 "2019-03-21T15:30:05Z")

</div>

I agree that this feels like an arbitrary limitation, especially given that this works exactly as expected:

```swift
let maybeInt = 1 as Int?
let anything = maybeInt as Any

let opened = anything as? Int?
// error: cannot downcast from 'Any' to a more optional type 'Int?'

func dynamicCast<T>(_ value: Any, to _: T.Type) -> T? {
  if let value = value as? T {
    return value
  } else {
    return nil
  }
}

if let opened = dynamicCast(anything, to: Int?.self) {
  print("got an optional Int: \(opened)")
} else {
  print("it's something else entirely")
}

```

---

_[View the full topic](https://forums.swift.org/t/casting-from-any-to-optional/21883)._
