Getting an optional held in an optional

I call the following code and get an Optional<Any>, whose .some case contains an Optional<Int>

let value = subject[keyPath: keyPath]

Any ideas how I can get the .some value, or even nil from the Optional<Int> ?

Maybe

if case .some(.some(let v)) = value {
  // Do something
}

Unfortunately, the part between asterisks gives an error "Pattern cannot match values of type 'Any'"

Ah, try:

if case .some(Optional<Any>.some(let v)) = value {
  // Do something
}

or just simply:

if let unwrapped = value as? Int {
  // Do something
}

Yessss!!! Thank you so much :grin:

let x = value as? Int

Unfortunately, this can't work as, in the surrounding code, it is not possible to determine that the inner .some is an Int. All we can know is that it is an Any and, of course, everything will cast to Any :wink:

…what?

You specifically said in the original post:

Indeed I did, but only as a means of describing the ultimate reality. That did not include the fact that the inner type can only be accessed as an Optional<Any>.

So, at the point in the code in question, the only way I can work with the value is an Optional<Optional<Any>> and it is sufficient to have the the inner Any as it is going to be passed to String(describing:_)

Terms of Service

Privacy Policy

Cookie Policy