gpt4 book ai didi

swift - 元素与通用类型

转载 作者:搜寻专家 更新时间:2023-11-01 05:51:46 27 4
gpt4 key购买 nike

我想知道为什么 Swift 使用 Element而不是 Generic <T>在下面的例子中。

Element 之间有什么区别?对比T

enter image description here

最佳答案

来自 Generics :

Type Parameters

Type parameters specify and name a placeholder type, and are written immediately after the function’s name, between a pair of matching angle brackets (such as <T>).

Naming Type Parameters

In most cases, type parameters have descriptive names, such as Key and Value in Dictionary<Key, Value> and Element in Array<Element>, which tells the reader about the relationship between the type parameter and the generic type or function it’s used in. However, when there isn’t a meaningful relationship between them, it’s traditional to name them using single letters such as T, U, and V, such as T in the swapTwoValues(_:_:) function above.

所以

func createArray<Element>(element: Element) -> [Element] { ... }
func createArray<T>(element: T) -> [T] { ... }
func createArray<Rumpelstilzchen>(element: Rumpelstilzchen) -> [Rumpelstilzchen] { ... }

是相同的函数。这里的占位符类型是返回数组的元素类型,因此 Element是一个合适的“描述性名称”。

但除此之外没有任何区别,是否由您为占位符选择一个名称,在可读性和简洁性之间取得平衡。

关于swift - 元素与通用类型 <T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55542757/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com