Swift中可选协方差如何工作 [英] How does Optional covariance work in Swift

查看:82
本文介绍了Swift中可选协方差如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中Optional的协方差如何工作?

How does covariance work for Optionals in Swift?

假设我编写以下代码:

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

nativeOptionalView = nativeOptionalButton

它可以编译并正常工作.但是,如果我将MyOptional定义为

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

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

并输入以下内容:

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

myOptionalView = myOptionalButton

我得到了错误:

错误:无法将类型"MyOptional<UIButton>"的值分配给类型"MyOptional<UIView>"

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

我了解为什么MyOptional会发生此错误,我不明白为什么Optional不会发生此错误.

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

推荐答案

不是. Swift目前不支持自定义协变泛型.

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

Swift类型检查器是针对每个表达式而不是全局的(如Haskell中一样).此任务是处理. github.com/apple/swift/tree/master/lib/Sema"rel =" noreferrer> lib/Sema .然后,约束系统尝试匹配类型,然后对

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.

这篇关于Swift中可选协方差如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆