Swift: Compiler's conversion from type to optional type

╄→尐↘猪︶ㄣ 提交于 2019-12-30 11:54:32

问题


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")

回答1:


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:

  • http://htmlpreview.github.io/?https://github.com/apple/swift/blob/master/docs/archive/LangRef.html

  • htmlpreview of the LangRef.html at July 25 2017 (from which state the information above has been cited)


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.



来源:https://stackoverflow.com/questions/45302816/swift-compilers-conversion-from-type-to-optional-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!