The following code compiles without warning:
Version 1:
var anything: Any
anything = "woof"
Makes sense... Any is any type, value type or reference type.
However, if we create an optional variable like a Double?
, this code throws a warning:
Version 2:
var anything: Any
let aDouble: Double? = 3
anything = aDouble
But this code does not throw a warning:
Version 3:
enum AnEnum<T>: {
case first
case second (T)
}
var anEnum: AnEnum<String> = .first
anything = anEnum
You can rationalize that version 2 throws a warning because Any
is not an Optional
type, and Double?
is an Optional
type. Trying to assign an Optional to a non-optional type is sort of a type mismatch.
However, under the covers, an Optional
is an enum
with a .none
case, and with a .some
case, where the .some
case has an associated value. My version 3 uses an enum
, AnEnum
, that also has 2 cases, the second of which has an associated value. The AnEnum
type is nearly identical to the Swift native Optional
type.
Why is assigning an AnEnum value to anything
ok, but assigning an Optional value to anything
is not ok?
(I started to answer this question: Swift dictionary with mix types (optional and non-optional))
And then realized that I didn't really know the answer.