How does Swift allow assignment of an optional type to a non optional type?

For example, this works:
var x: Int? = 3

I know that optionals are just an enum with an associated value so I was wondering if this is something that is achievable by normals users or if this is compiler magic.

It's compiler magic, non-optional values can be automatically promoted to optionals in certain contexts.

You can narrowly achieve the same thing for literals (like nil, 123, 123.45, true, "string", ["array"], ["dict": 123], etc,) using the ExpresisbleByXLiteral protocols.

Swift doesn't have anything like C#'s user defined conversion operators that would allow you to implement implicit conversion like this in the general case (for non-literal values).

I have mixed feelings. There are certainly times when they're really cool and clean up noisy code. But it also makes it harder to read code if you're not super attentive and don't have access to an IDE to assist your navigation (e.g. you're reading code on GitHub in your browser).

1 Like
Terms of Service

Privacy Policy

Cookie Policy