swift - Swift 嵌套泛型参数推断
问题描述
斯威夫特 5.1 。
考虑以下代码。确切地说,我没有问题,但是我的代码有点多余,而且有点烦人,所以我想知道是否有办法告诉 Swift 推断其中一个泛型参数。
public class X0 {
}
public class X1: X0 {
}
public class C0<CONTAINED> {
public var value: CONTAINED
public init(_ value: CONTAINED) {
self.value = value
}
}
public class C1<T: X0>: C0<T> {
}
//public class CA<BOX: C0> { // ERROR Reference to generic type 'C0' requires arguments in <...>
public class CA<BOX: C0<T>, T> { // It's inconvenient that I have to give T as a parameter of the outer class; seems like it could be inferred
}
public func test() {
// let v: CA<C1<X1>> // ERROR Generic type 'CA' specialized with too few type parameters (got 1, but expected 2)
let v: CA<C1<X1>, X1> // This here is a little inconvenient to type, particularly when the class names are longer.
}
两者X1
必须相等,似乎 - 我试过了CA<C1<X0>,X1>
,CA<C1<X1>,X0>
以防万一我错过了一些逻辑问题,但它给了我两者的错误,所以我认为两者必须完全相等,所以理论上应该允许推理, 至少。
有没有办法告诉 Swift 推断出重复的类型参数?_
我在几个地方尝试过,并省略了参数,但它给了我错误。
解决方案
- 您只能使用协议对其进行清理。
- 您不能将协议放在类型中,因此命名必须看起来像 Objective-C。
- 使用骆驼箱!
public class C0<> {
public var value:
public init(_ value: ) {
self.value = value
}
}
public protocol C0Protocol {
associatedtype
}
extension C0: C0Protocol { }
public class CA<C0: C0Protocol> { }
public func test() {
let v: CA< C1<X1> >
}
推荐阅读
- ruby-on-rails - 无法验证 SSL 证书
- python - 在 fig Python 中给子图不同的方向
- python - django html模板未从模型的通用视图加载
- excel - 个人宏工作簿项目仍然可见,代码随机丢失
- python - Python中的有理数
- javascript - 需要弄清楚视频的 CSS 选择器
- android - Xamarin 在不同的进程问题中分离服务
- python - 你将如何在 google protobufs for python 中设置 DoubleValue
- python - 如何在python中为Matrix选择特定列
- json - “方法不允许” Graph API 发布到批处理端点