Naming Type Parameter

In simple cases where a generic function or generic type refers to a single placeholder type (such as the swapTwoValues generic function above, or a generic collection that stores a single type, such as Array), it is traditional to use the single-character name T for the type parameter. However, you can use any valid identifier as the type parameter name.

If you are defining more complex generic functions, or generic types with multiple parameters, it is useful to provide more descriptive type parameter names. For example, Swift's Dictionary type has two type parameters - one for its keys and one for its values. If you were writing Dictionary yourself, you might name these two type parameter Key and Value to remind you of their purpose as you use them within your generic code.

Always give type parameters UpperCamelCase names (such as T and Key) to indicate that they are a placeholder for a type, not a value.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容