The following code compiles without warning:
var anything: Any
anything = "woof"
Makes sense... Any is any type
Quite simply, it's because Any is like a Roach Motel for Optionals.
The Roach Motel is a cockroach trap whose motto is, "Roaches check in, but they don't check out." The same is true for Any and Optionals. You can put an Optional into an Any, but you can never get it out again.
To see what I mean, let's first put something else into an Any and get it out again:
let s : String = "howdy"
let any : Any = s
let s2 = any as! String
s2 // "howdy"
Now let's try that with an Optional:
let s : String? = "howdy"
let any : Any = s
let s2 = any as! String? // error
Ooops! You can't cast a nonOptional "down" to an Optional, so the original Optional is lost.
The thing wrapped by the Optional is not lost. You can still unwrap it:
let s : String? = "howdy"
let any : Any = s
let s2 = any as! String
s2 // "howdy"
But now s2
is a String, not an Optional. The Optional is gone for good. You can't get it out. You can't find out that what was put into the Any was an Optional. It's gone.
So that's why putting an Optional into an Any always elicits a warning. The compiler is saying: "You can do this, but do you really understand what you're doing?" And if you do, there are ways to silence the warning (and the error message tells you what they are).