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

后端 未结 5 1636
借酒劲吻你
借酒劲吻你 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:32

    Here is how AnEnum different from Optional.

    You can mimic Optional by implementing everything Optional does. However, what you create is another independent "Optional" that is not interoperable with Swift built-in Optional. For example, you can implement ExpressibleByNilLiteral so that you can assign nil to AnEnum which resolves to .first. Just like how Optional resolves nil to Optional.none

    enum AnEnum : ExpressibleByNilLiteral {
    
        case first
        case second (T)
    
        public init(nilLiteral: ())
        {
            self = .first
        }
    
    }
    
    var anEnum: AnEnum = nil
    var anything = anEnum
    

    However, this nil will be DIFFERENT from the nil of Optional.

    As suggested by the implementation, Optional does not use the value of nil directly, it just resolves nil literal to Optional.none which it actually stores.

    Same as other Enum, Optional.none is just an unknown value (at least you couldn't guarantee it to equal any other values) since no rawValue is specified.

    Your nil will be AnEnum.first while Optional's nil will be Optional.none. Optional.none and AnEnum.first are two different unrelated Enum values. Optional won't consider AnEnum.first as Optional.none since they are different and the only way you get Optional.none is by assigning nil literal to Optional.

    This explains why you can assign AnEnum, which you think is nearly identical to Swift native Optional, to Any with no problem but assigning an actual Swift native Optional to Any does causes problem. Because your custom "Optional" does not mean anything special other than an Enum to the compiler. The compiler only treats Swift native Optional specially even it is technically just an Enum.

提交回复
热议问题