Boon
Boon

Reputation: 41480

Swift: Compiler's conversion from type to optional type

It looks like compiler automatically converts a type into an optional type when needed, even though there is no inheritance relationship here.

Where in the documentation is this behavior specified?

func test(value: String?) {
    // String passed in is now an optional String instead.
    print(value ?? "")
}

// Pass an actual string
test(value: "test")

Upvotes: 1

Views: 387

Answers (1)

dfrib
dfrib

Reputation: 73186

This behaviour is actually explicitly documented in a well-hidden corner of the docs folder of the Swift github repo.

Citing swift/docs/archive/LangRef.html [changed some formatting; emphasis mine]:

Types

type ::= attribute-list type-function
type ::= attribute-list type-array

...

type-simple ::= type-optional

Swift has a small collection of core datatypes that are built into the compiler. Most user-facing datatypes are defined by the standard library or declared as a user defined types.

...

Optional Types

Similar constructs exist in Haskell (Maybe), the Boost library (Optional), and C++14 (optional).

type-optional ::= type-simple '?'-postfix

An optional type is syntactic sugar for the library type Optional<T>. This is a enum with two cases: None and Some, used to represent a value that may or may not be present.

Swift provides a number of special, builtin behaviors involving this library type:

  • There is an implicit conversion from any type T to the corresponding optional type T?.

...

See the htmlpreview.github.io rendering of the HTML for easier overview of the docs than the .html source:


Now, this is me speculating, but the reason why this is not very publicly available (and also not entirely up to date; placed in the archive sub-folder, and still using the old None and Some cases rather than none and some, respectively) is probably because the Swift team (no longer?) see a reason for general Swift users to know details regarding the compiler "magic" associated with the very special type Optional, but rather focuses on the use cases and grammar (in the context of the Swift language and not its compiler) of Optional.

Upvotes: 3

Related Questions