Swift 中泛型类的类型别名 [英] typealias of generic class in Swift

查看:31
本文介绍了Swift 中泛型类的类型别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按如下方式制作泛型类的类型别名

I am trying to make a typealias of a generic type class as follows

class Cars<T> {
  ...
}

typealias SportCars = Cars

但我收到如下编译错误 Reference to generic type 'Cars' requires argument in <...>

but I am getting a compile error as follow Reference to generic type 'Cars' requires argument in <...>

推荐答案

现在,正如您所发现的,您无法使用泛型来做到这一点.

Right now, you can't do this with generics, as you've discovered.

typealias Foo = Array
// Doesn't work: Reference to generic type 'Array' requires argument in <...>

Swift 编程语言 iBook 章节类型别名声明"实际上并没有说明哪些类型不能被别名化.但看起来部分类型(如没有指定占位符的泛型)是不允许的.

The Swift Programming Language iBook chapter "Type Alias Declaration" doesn't actually state anything about which types cannot be aliased. But it simply looks like that partial types (like generics without placeholders specified) are not allowed.

如果您认为 Swift 应该做这件事,请向 Apple 提交 Radar(错误报告).

If you feel that this something Swift should do, file a Radar (bugreport) with Apple.

在研究这个答案时,我注意到 partial type 问题不仅影响 typealias,而且在其他地方也可见:

While researching for this answer, I noticed that the partial type problem not only affects typealias but is visible elsewhere as well:

let foo = Array.self
// Doesn't work: Cannot convert the expression's type 'Array<T>.Type' to type 'Array<T>.Type'
// … which is a very confusing error.

var bar: Array.Type
// Doesn't work: Reference to generic type 'Array' requires arguments in <...>

let bar: Array.Type = Array.self
// …/usr/bin/swift: Segmentation fault! :-)

如果您指定占位符类型,所有这些都可以工作:

All of these work if you specify the placeholder types:

typealias Foo = Array<Int> // Works
let foo = Array<Int>.self // Works

这篇关于Swift 中泛型类的类型别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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