Reputation: 16813
I wonder why Swift uses Element
rather than Generic <T>
in the following example.
What is the difference between Element
vs T
Upvotes: 2
Views: 1086
Reputation: 299605
T
is not particularly traditional. In FP, Backus uses T
, but ML, from around the same time, uses a
. Haskell uses a
, Scala uses A
. There's a mix of choices.
Swift, however, has strong reasons to use descriptive names. First, it's a quite descriptive language. Types are named with fully spelled-out words. Methods typically are literate in construction. Variables and properties are rarely abbreviated. There's no reason that type parameters should be uniquely obscure.
It also matches well with associated types which are quite naturally verbose. What would you call Collection's index type besides Index
? Why should its "element" type be specially abbreviated? And if Array implements Collection, why should it create a distinct name (T) that it would then have to associate with Collection's Element? Why would you special-case all this just to make the type name unintuitive?
The deeper question would be, why wouldn't Array's element be called Element?
Upvotes: 2
Reputation: 540045
From 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 inArray<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 theswapTwoValues(_:_:)
function above.
So
func createArray<Element>(element: Element) -> [Element] { ... }
func createArray<T>(element: T) -> [T] { ... }
func createArray<Rumpelstilzchen>(element: Rumpelstilzchen) -> [Rumpelstilzchen] { ... }
are identical functions. Here the placeholder type is the element type of the returned array, therefore Element
is a suitable “descriptive name.”
But it makes no difference otherwise, is it up to you to choose a name for the placeholder, balancing between readability and conciseness.
Upvotes: 6