How does Optional covariance work in Swift

邮差的信 提交于 2020-06-10 02:43:20

问题


How does covariance work for Optionals in Swift?

Say I write the following code:

var nativeOptionalView: Optional<UIView>
let button = UIButton()
nativeOptionalView = .Some(button)
var nativeOptionalButton = Optional.Some(button)

nativeOptionalView = nativeOptionalButton

It compiles and works just fine. However if I define MyOptional as

enum MyOptional<T> {
    case Some(T)
    case None
}

And write the following:

var myOptionalView: MyOptional<UIView>
let button = UIButton()
myOptionalView = .Some(button)
var myOptionalButton = MyOptional.Some(button)

myOptionalView = myOptionalButton

I get the error:

error: cannot assign value of type 'MyOptional<UIButton>' to type 'MyOptional<UIView>'

I understand why this errors happens with MyOptional, what I don't understand is why it doesn't happen with Optional.


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/37352122/how-does-optional-covariance-work-in-swift

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