How do I test nested Optional<Any> for nil?

Quite an unusual case, I agree. Couldn't find a solution though :(

let nestedAnyNil: Any? = Optional<Any>.some(Optional<Any>.none)
print(nestedAnyNil == nil)

output is false, which is kinda understandable.

If you want to flatten an arbitrary-depth Any? down to a single layer of optionality, you might find the thread Challenge: Flattening nested optionals relevant.

1 Like

screams inside

2 Likes

Thanks for the link, really interesting (and also effective). IMO Swift should be able to do this out of the box, just like with nested try optionals...

If it did it should at least have new syntax. The current behavior is correct imho and the least surprising. It does exactly what I would expect and correctly differentiates between nil and .some(nil), which are two very different values.

I do agree that having some means of flattening nested optionals have some value.

1 Like

Yeah, this is what I meant, no need to break existing behaviour (though I think flattening try? nested optionals might have broken some code :slight_smile:)

The difficulty, as evidenced by this thread, comes when you have an Any? that wraps another Optional.

It is easy to test for .none, but quite difficult to test for .some(.none).

Why do you want to do this? I've seen people ask it a handful of times, but I've never seen a case where it makes sense. (That inner Optional<Any>.none in your contrived example is a tip-off of that: there wasn't a good type to use there, so maybe it's not the right placeholder.)

I'm using a MsgPack package which produces nested nils (and not NSNulls like Foundation JSONSerialization) in case of null value of key :|

I see, and MsgPack has an untyped null (or rather a separately-typed null), rather than optional values. I think I would have recommended they make their own Null type rather than using Optional<Any>, but I guess that's not under your control…