How does Optional covariance work in Swift

前端 未结 2 502
星月不相逢
星月不相逢 2021-02-13 17:14

How does covariance work for Optionals in Swift?

Say I write the following code:

var nativeOptionalView: Optional
let button =         


        
相关标签:
2条回答
  • 2021-02-13 17:43

    While I agree that there is probably some "compiler magic" going on, this can be accomplished in your custom implementation by casting the button to a UIView, e.g.

    var myOptionalButton = MyOptional.Some(button as UIView)
    

    or

    var myOptionalButton: MyOptional<UIView> = .Some(button)
    
    0 讨论(0)
  • 2021-02-13 17:44

    It doesn't. Swift does not support custom covariant generics for now.

    The Swift type checker is per expression, not global (as in Haskell). This task is handled by the Semantic Analysis in lib/Sema. The constraint system then tries to match the types and special cases of covariance are then handled for collections, and optionals.

    This was a language design decision. You should be able to do everything you need with the built-in collection types and optionals. If you aren't you should probably open a radar.

    0 讨论(0)
提交回复
热议问题