2

I have seen several questions regarding "expression implicitly coerced from an Optional to Any"(such as this and this), but I did not find one explaining the reason why Optional is not "included" in Any, since, according to the Apple's Swift Standard Library, Optional is a generic enum type.

Any parameters are expected for the print function, so providing Optional would give the warning message. However, since Optional is an enum type, shouldn't it be an Any type as well? Why is Optional, as an enum type, not part of the Any type such that the compiler needs to convert Optional to Any?

qsmy
  • 383
  • 3
  • 14

1 Answers1

1

The purpose of Optional is to prevent you from accidentally calling methods on or accessing properties of variables which are nil.

You are right that Optional can be assigned to Any. Anything can be assigned to Any. But look what happens now! I have transformed a value that can be nil into a non-optional type Any! If somehow this value is passed to somewhere else and some other programmer (or you in the future) would assume that it has a non-nil value.

Therefore, the compiler warning is there to remind you that you may have forgotten to unwrap your optionals.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • The actual reason (SE-0140) was the bridging between Objective-C `id` and `Any`, as pointed out in https://stackoverflow.com/a/52508680/1187415. – Martin R Feb 09 '19 at 08:37