# generics

[Swift](../..) ⟩ [type](..) ⟩ [category]() ⟩ generics&#x20;

{% hint style="success" %}
Also called <mark style="color:purple;">generic types</mark>, <mark style="color:yellow;">code that works for multiple types</mark>.
{% endhint %}

```swift
// (automatically synthesized Hashable)
struct Pair<T: Hashable, U: Hashable>: Hashable {

    let left: T
    let right: U
    
    // convenience init
    init(_ left: T, _ right: U){
        self.left = left
        self.right = right
    }
}

// ⭐️ 使用 Pair 時，不需特別指定 <T, U>
let pair = Pair("Joe", 20)      
let dict = [pair: "friend"]
```

{% tabs %}
{% tab title="🔴 主題" %}
* [generics-and-subtypes](generic-types/generics-and-subtypes "mention")
* [generic](protocol/generic "mention")
{% endtab %}

{% tab title="⭐️ 重點" %}
{% hint style="info" %}
<mark style="color:purple;">Generic</mark> code is turned to <mark style="color:orange;">specialized</mark> code at <mark style="color:orange;">compile time</mark>.
{% endhint %}
{% endtab %}

{% tab title="📘 手冊" %}
* [Swift](https://docs.swift.org/swift-book/documentation/the-swift-programming-language) ⟩ [Generics](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/generics/)
{% endtab %}

{% tab title="📗 參考" %}
* [ ] Sundell ⟩ [Discover Generics](https://www.swiftbysundell.com/discover/generics/)
* [ ] TensorFlow ⟩ [Protocol-oriented programming & generics](https://www.tensorflow.org/swift/tutorials/protocol_oriented_generics)
* [ ] AppCode ⟩ [詳解 Swift 各種 Type Polymorphism](https://www.appcoda.com.tw/swift-polymorphism/) #todo
* [ ] [Master Swift Generics: A practical guide to code reuse](https://matteomanferdini.com/swift-generics/)
* [ ] Swift in Depth, Ch. 7, Generics
{% endtab %}

{% tab title="👥 相關" %}
* [hashable](protocol/hashable "mention") - type parameter 或 generic type 本身有時必須是 Hashable, 例如：當作 Dictionary 的 Key 或是當作 Set 的元素。
* [operator](../../pattern-matching/operator "mention") - generic operator (for <mark style="color:red;">**pattern matching**</mark>)
{% endtab %}

{% tab title="❓" %}
{% hint style="warning" %}
問：「 可以定義 <mark style="color:blue;">**`S<A>`**</mark> 又定義 <mark style="color:blue;">**`S<A, B>`**</mark> 嗎❓」

答：「 <mark style="color:red;">**不行**</mark>❗️(<mark style="color:red;">**`redeclaration of S`**</mark>) 」
{% endhint %}
{% endtab %}
{% endtabs %}
