为什么Swift中的类型推断不处理传递约束? [英] Why does type inference in Swift not deal with transitive constraints?

查看:114
本文介绍了为什么Swift中的类型推断不处理传递约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改这个问题,我想出了这个:

  class AllTogether< T:FooProtocol> {
func createContainer< U:T>(data:U){
Container< T>(someDataConformingFooProtocol:data)
}
}
FooProtocol
一个类协议,这应该工作: p>

  protocol FooProtocol:class {...} 

但是,我们仍然收到错误:

 错误:从非协议继承,非类类型'T'
错误:参数类型'U'不符合预期类型'FooProtocol'

这两条消息似乎都是错误的。我错过了什么?



在Swift中,子类型关系是不是传递的?

解决方案

该函数添加了一个不必要的附加关系。



容器正在使用T类型的对象进行初始化。



如果U是T的子类,那么任何可以用

  func createContainer< U:T>(data:U)

也可以使用

调用

  func createContainer(data:T)

所以基本上这个函数的功能似乎应该是可能的(也可能在某个时刻,Swift的泛型应该会被彻底改进/改进),但无论如何它是没有意义的。



只需使用它:

  func createContainer(data:T){
Container< T>(someDataConformingFooProtocol:data)
}


Tinkering around with this question, I came up with this:

class AllTogether<T: FooProtocol> {
    func createContainer<U: T>(data: U){
        Container<T>(someDataConformingFooProtocol: data)
    }
}

My understanding is that this should work if we make FooProtocol a class protocol:

protocol FooProtocol: class { ... }

However, we still get errors:

Error: inheritance from non-protocol, non-class type 'T'
Error: argument type 'U' does not conform to expected type 'FooProtocol'

Both messages seem to be wrong. What am I missing?

Is the subtype relation not transitive in Swift?

解决方案

The function adds an additional relation that is unnecessary.

Container is looking to be initialized with an object of type T.

If U is a subclass of T, then anything that can be called with

func createContainer<U: T>(data: U)

can also be called with

func createContainer(data: T)

So basically what the function is doing seems like it should be possible (and may be at some point. Swift's generics is due to be overhauled/improved) but it is pointless anyway.

Just use this instead:

func createContainer(data: T){
    Container<T>(someDataConformingFooProtocol: data)
}

这篇关于为什么Swift中的类型推断不处理传递约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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