The following code compiles without warning:
var anything: Any
anything = "woof"
Makes sense... Any is any type
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.