Explicit type name for implicitly unwrapped optional type

Is there an explicit type name for implicitly unwrapped optional type?

Int?  <-> Optional<Int>
Int!  <-> ???

Both Int? and Int! are Optional<Int> with added extra behaviour

  • Int? has default initialization

  • Int! has default initialization and coercion to Int

Depending on your interpretation either both of them have the same explicit name, or they both lack it

(A long time ago Int! was a different type, named something like ImplicitlyUnwrappedOptional, but today they both are just Optional)

5 Likes

Hmm... "Int?" looks like a shortcut for "Optional"

struct Bar {
    var z: Int
}
struct Foo {
    var x: Bar?
    var y: Optional<Bar>
}

There's a slight difference now that Foo's autogenerated initialiser is effectively:

init(x: Int? = nil, y: Int?)

but otherwise the two are equivalent. E.g. on the use side both require postfix ? or !:

foo.x.z // error
foo.y.z // error
foo.x?.z
foo.y?.z
foo.x!.z
foo.y!.z

"Int!" also looks like a shortcut for some full form like your mentioned "ImplicitlyUnwrappedOptional"... which no longer exists.

Int! is not exactly Optional:

struct Foo {
    var x: Bar!
    var y: Optional<Bar>
}

foo.x.z // ok
foo.y.z // error  <•••••• the difference
foo.x?.z
foo.y?.z
foo.x!.z
foo.y!.z

Then there's no explicit name for Int!

This blog post from swift.org describes how Implicitly Unwrapped Optionals are now implemented.

It provides a nice mental model for how to think about them and also goes into a good deal of detail.

8 Likes

Yes, as an example, normally you don't need to explicitly initialize optional var properties, but if you spell it out:

struct S {
    var p: Optional<Int>
    init() {}              // ❌ Return from initializer without initializing all stored properties
}
1 Like