Swift:泛型类中的声明 [英] Swift: Declaration in generic class

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

问题描述

假设我有一个泛型类:

  class SomeClass< Element> {
//这有什么区别:
var array:[SomeClass]!

//以及此声明:
var array2:[SomeClass< Element>]!

$ / code>

这些声明之间的区别是什么?

解决方案

如果没有泛型参数,泛型不能存在,因此省略泛型意味着您希望编译器推断该类型。 b

在这种情况下,推断的逻辑类型是元素



请注意,这仅仅是因为你在 SomeClass 声明中使用了 SomeClass 。它不适用于不同的泛型类。



泛型参数的类似推断可用于变量声明:

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


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.

Note that this works only because you have used SomeClass inside SomeClass declaration. 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>

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

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