LoginSignup
9
7

ジェネリクスの型パラメータの命名について

Last updated at Posted at 2017-03-12

Swift実践入門 を読んでいて、ジェネリクスの型パラメータの命名が気になり少し調べてみました。

Swiftのリファレンス読むと、型パラメータには...
「基本的に説明的な名前をつけるが、意味が無いときは伝統的にT,V,Uをつけるのが一般的」(だいぶ端折った) と記載があり、個人的にTやUの意味が気になりました。

下記Swiftのドキュメントから

Naming Type Parameters

In most cases, type parameters have descriptive names, such as Key and Value in Dictionary and Element in Array, 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.

ジェネリクスとはJavaで出会ったことを思い出し、Javaの命名規約を見たところ、EはElement、TはTypeの略と分かり、SやUにはn番目の型以上の意味が無いことが分かりました。そしてsingle, uppercase letters だけではアプリケーションのプログラミングにカジュアルにジェネリクスが登場する現代のプログラミング環境では流石に意味が曖昧すぎるとも感じました。(T,U,V,W,X,Y,Zとつけていくことを想定していそうです、Wまでいった時点で設計がおかしい可能性が高いと思いますが)

Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.

The most commonly used type parameter names are:

E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

ちなみにAPIKit内部でも利用されているResultを抜粋するとsuccessの時はT、エラーの時はErrorと意味を表現できる最低限の命名を使っています。

/// An enum representing either a failure with an explanatory error, or a success with a result value.
public enum Result<T, Error: Swift.Error>: ResultProtocol, CustomStringConvertible, CustomDebugStringConvertible {
	case success(T)
	case failure(Error)

swap関数は2値を入れ替えるだけなのでシンプルにTのみでした。

/// - Precondition: `a` and `b` do not alias each other.
public func swap<T>(_ a: inout T, _ b: inout T)  

まとめ

  1. 標準ライブラリの関数など型の意味が自明、スコープが短いケースはTなど省略形が良さそう
  2. 意味が非自明で正確に表現する必要があるなら具体的な命名が良い <E> よりも <Error>
9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7