# Dynamic casting Any to a runtime optional type

**URL:** <https://forums.swift.org/t/dynamic-casting-any-to-a-runtime-optional-type/52127>\
**Category:** Using Swift\
**Tags:** type-casting, metatype, metadata, any\
**Created:** [September 16, 2021, 10:15am UTC](https://forums.swift.org/t/dynamic-casting-any-to-a-runtime-optional-type/52127 "2021-09-16T10:15:36Z")\
**Posts on this page:** 1\
**Showing post:** 9

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [September 16, 2021, 1:51pm UTC](https://forums.swift.org/t/dynamic-casting-any-to-a-runtime-optional-type/52127/9 "2021-09-16T13:51:39Z")

</div>

We can use this answer from the thread [Challenge: Flattening nested optionals](https://forums.swift.org/t/challenge-flattening-nested-optionals/24083/4):

```swift
protocol Flattenable {
  func flattened() -> Any?
}

extension Optional: Flattenable {
  func flattened() -> Any? {
    switch self {
    case .some(let x as Flattenable): return x.flattened()
    case .some(let x): return x
    case .none: return nil
    }
  }
}

```

To write a function like this:

```swift
func flatten(_ a: Any) -> Any? {
  return (a as? Flattenable)?.flattened()
}

```

And then you can use:

```swift
for p in [aa, bb] {
    print(flatten(p) == nil ? "NIL" : "Non Nil")
}

```

• • •

If you just want the boolean result, you could do:

```swift
func isActuallyNil(_ a: Any) -> Bool {
  return (a as? Flattenable)?.flattened() == nil
}

```

Or if you want to extract the innermost wrapped type into an `Any.Type`, that can be done using the solutions from [Challenge: Finding base type of nested optionals](https://forums.swift.org/t/challenge-finding-base-type-of-nested-optionals/25096).

---

_[View the full topic](https://forums.swift.org/t/dynamic-casting-any-to-a-runtime-optional-type/52127)._
