Why can't you assign an Optional to a variable of type `Any` without a warning?

后端 未结 5 1665
借酒劲吻你
借酒劲吻你 2021-01-02 22:54

The following code compiles without warning:

Version 1:

var anything: Any
anything = "woof"

Makes sense... Any is any type

5条回答
  •  轮回少年
    2021-01-02 23:20

    It has its own history.

    Starting with this feature, in the era of Swift 3.

    SE-0116 Import Objective-C id as Swift Any type(So, called id-as-Any in the history of Swift, which is the worst thing in the history, in my opinion.)

    (Until then, Any was not such a popular type in Swift programmers.)

    It includes a fantastic new feature, universal bridging conversion, which guarantees literally Any values in Swift can be convertible to non-null id when bridging to Objective-C.

    But this feature caused a huge number of disastrous tragedies, called _SwiftValue.

    In the original conversion first introduced in Swift 3, Optional was converted to _SwiftValue regardless of whether it was nil or non-nil. It is completely useless in Objective-C world, almost all operations on _SwiftValue caused a crash, which could not have found till runtime, throwing away the goodness of strongly typed language.

    So, Swift team needed to introduce a new feature immediately:

    SE-0140 Warn when Optional converts to Any, and bridge Optional As Its Payload Or NSNull

    Since this feature introduced in Swift 3.0.1, nils are bridged to NSNull and non-nil values are bridged based on the unwrapped values.

    The feature also includes Warning when Optional is converted to Any to avoid unintentional misuse of Optional to Any.

    The warning you have described started at this time in the Swift history.


    The behavior of Optional is backed by many compiler magics (so-called by Swift team members), for example, you cannot make use of simple if-let for other enum types, you cannot use Optional Chaining with your custom enums. Swift compiler treats Optional as a special thing than normal enums.

提交回复
热议问题