Casting from Any to Optional

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

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")
}
2 Likes