简体   繁体   English

Swift:通用类中的声明

[英]Swift: Declaration in generic class

Let's say I have a generic class: 假设我有一个通用类:

class SomeClass<Element> {
  // What is the difference between this:
  var array: [SomeClass]!

  // and this declaration:
  var array2: [SomeClass<Element>]!
}

What is the difference between those declarations? 这些声明之间有什么区别?

A generic type cannot exist without its generic argument, therefore omitting the generic type means that you want the compiler to infer the type. 没有泛型参数就无法存在泛型类型,因此省略泛型类型意味着您希望编译器推断该类型。

In this case the logical type to be inferred is Element . 在这种情况下,要推断的逻辑类型是Element

Note that this works only because you have used SomeClass inside SomeClass declaration. 请注意,这仅是因为您已在SomeClass声明中使用SomeClass It wouldn't work for a different generic class. 它不适用于其他泛型类。

A similar inferring of generic arguments can be used in variable declarations: 可以在变量声明中使用类似的通用参数推断:

let instance: SomeClass = SomeClass<Int>()
let array: Array = [1] // Array<Int>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM