Why can't you assign an Optional to a variable of type `Any` without a warning?

后端 未结 5 1661
借酒劲吻你
借酒劲吻你 2021-01-02 22:54

The following code compiles without warning:

Version 1:

var anything: Any
anything = "woof"

Makes sense... Any is any type

5条回答
  •  温柔的废话
    2021-01-02 23:29

    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).

提交回复
热议问题