Swift:泛型类中的声明

编程入门 行业动态 更新时间:2024-10-26 00:30:18
本文介绍了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:泛型类中的声明

本文发布于:2023-11-09 10:30:00,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类中   声明   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!