… a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. This approach, pioneered by ML in 1973, permits writing common functions or types that differ only in the set of types on which they operate when used, thus reducing duplication.

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.

Generics are one of the most powerful features of Swift , and much of the Swift standard library is built with generic code. … For example, Swift ’s Array and Dictionary types are both generic collections. You can create an array that holds Int values, or an array that holds String values, or indeed an array for any other type that can be created in Swift . Similarly, you can create a dictionary to store values of any specified type, and there are no limitations on what that type can be. …

泛型的解决之道

（再次紧记学习泛型的目的，我们依旧假设 Swift 的数组类型的内置的函数，indexcontains ，不存在。）

关于 Equatable 协议

exists 函数中 <T: Equatable > 标注是什么呢？它叫做类型约束，它规定了”那个类型参数必须继承自一个具体的类，或者遵守一个特定的协议或是协议组合。我指定了 exists 函数参数，item: TinArray: [T], 必须是类型 T, 而类型 T 必须遵守协议 Equatable 协议，为什么是这样的呢?

遵守 Equatable 协议

• 让类遵守 Equatable 协议
• 重载类实例的 == 操作符

扩展阅读

Adding Equatable conformance to your custom types means that you can use more convenient APIs when searching for particular instances in a collection. Equatable is also the base protocol for the Hashable and Comparable protocols, which allow more uses of your custom type, such as constructing sets or sorting the elements of a collection.

Equatable 协议也是 Hashable 协议和 Comparable 协议的基础协议。这允许你使用更多的自定义类型，比如构建集合或者排序集合中的元素。