0

In Swift, casting an optional constant to Any is legal, for example:

let nilValue: String? = nil
let any: Any = nilValue

without the need to declare any as optional Any (Any?)

however, the surprising result for me is that:

print(any == nil) // false
print(any) // nil

Which seems to be conflict.

I could find a workaround to check whether any is nil or not, however my question is what is the reason for such a behavior?

Please note that if I declared any as:

let any: Any? = nilValue

the output of

print(any == nil)

would be true.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • @vacawama thanks mate. Do you think it might be better if I delete the question? – Ahmad F May 10 '18 at 14:35
  • That's up to you. Your question has a different title and might make it easier for another person to find the answer when searching. – vacawama May 10 '18 at 14:38
  • It would be a good idea to up vote the duplicate's answer though if you haven't already. – vacawama May 10 '18 at 14:46
  • @vacawama ya sure! I prefer to do after I carefully read it – Ahmad F May 10 '18 at 14:49
  • @vacawama I think I got it. However, do you think that is it logical to be able to cast an optional string -for instance- as non-optional Any? I mean what's the point of it if (`any == nil`) never succeeds? – Ahmad F Jun 21 '18 at 07:56
  • The point of `Any` is that it can hold anything. It would change the definition of `Any` to say it can be anything but optionals. Optionals are a special syntactic sugar around the underlying enum implementation. The Swift language requires a var to be an optional in order to compare it to `nil`. My advice is to avoid using `Any` whenever possible, and definitely avoid putting an optional value into a non-Optional `Any` var. – vacawama Jun 21 '18 at 09:26
  • 1
    Many of the struggles around this involve the interaction with Objective-C. Swift changed from treating `id` as `AnyObject` to `Any` to make other interactions nicer, but resulted in sometimes treating optionals as `Any`. The compromise was to add a warning to the compiler if you try to assign an optional to an `Any` var. The compiler requires you to cast the value to `Any` to say "yeah, I know this is troublesome, but I really need it in this case". An example of when this is needed is trying to print an optional without unwrapping it: `print(someOptionalValue as any)`. – vacawama Jun 21 '18 at 09:56

0 Answers0