# some╱any╱generics

[Swift](https://lochiwei.gitbook.io/ios/swift) ⟩ [type](https://lochiwei.gitbook.io/ios/swift/type) ⟩ [category](https://lochiwei.gitbook.io/ios/swift/type/category) ⟩ some╱any╱generics

{% hint style="success" %}
[`some`](https://lochiwei.gitbook.io/ios/swift/type/category/some-any-generics/some), [`any`](https://lochiwei.gitbook.io/ios/swift/type/category/some-any-generics/any), [generics](https://lochiwei.gitbook.io/ios/swift/type/category/generic-types) 是三種<mark style="color:yellow;">特性不同的型別</mark>，比較如下：
{% endhint %}

<table data-header-hidden><thead><tr><th width="150">特性</th><th>some</th><th>any</th><th>generic</th></tr></thead><tbody><tr><td></td><td><a href="some-any-generics/some"><code>some</code></a></td><td><a href="some-any-generics/any"><code>any</code></a></td><td><a href="generic-types">generic</a></td></tr><tr><td>範例</td><td><pre class="language-swift"><code class="lang-swift">// implementer
func f() -> some Shape {
    Circle()
}

// user
let a = f() </code></pre></td><td><pre class="language-swift"><code class="lang-swift">// implementer
func g() -> any Shape {
// omitted ...
}

// user
let b = g() </code></pre></td><td><pre class="language-swift"><code class="lang-swift">// implementer
struct Container\<T> {
var value: T
}

// user
let c = Container(value: 42) </code></pre></td></tr><tr><td>型別決定者</td><td><span data-gb-custom-inline data-tag="emoji" data-code="1f477">👷</span> <a href="../../../master/term/roles/implementer">實現者</a></td><td><span data-gb-custom-inline data-tag="emoji" data-code="1f9d1-1f4bc">🧑‍💼</span> <a href="../../../master/term/roles/user">使用者</a></td><td><span data-gb-custom-inline data-tag="emoji" data-code="1f9d1-1f4bc">🧑‍💼</span> <a href="../../../master/term/roles/user">使用者</a></td></tr><tr><td>型別決定期</td><td><span data-gb-custom-inline data-tag="emoji" data-code="2699">⚙️</span> <mark style="color:green;">編譯期</mark></td><td><span data-gb-custom-inline data-tag="emoji" data-code="1f3ce">🏎️</span> <mark style="color:red;">執行期</mark></td><td><span data-gb-custom-inline data-tag="emoji" data-code="2699">⚙️</span> <mark style="color:green;">編譯期</mark></td></tr><tr><td>允許多型別</td><td><p><mark style="color:red;">否</mark>，<mark style="color:orange;">單型別</mark> (homogeneous type)</p><p></p><p><mark style="color:yellow;">對使用者隱藏具體型別</mark>，故稱為 <a href="some-any-generics/some">opaque type</a>。</p></td><td><p><mark style="color:green;">是</mark>，<mark style="color:green;">多型別</mark> </p><p>(heterogeneous type)</p><p></p><p><mark style="color:yellow;">將具體型別封裝起來</mark>的型別，故稱為 <a href="some-any-generics/any">boxed protocol type</a>。</p></td><td><p><mark style="color:orange;">介於是與否之間</mark> </p><p></p><p>使用者可指定不同的 <mark style="color:blue;"><code>T</code></mark>，因此<mark style="color:green;">可產生許多不同的具體型別</mark>。</p><p></p><p>不過一旦指定了 <mark style="color:blue;"><code>T</code></mark> ，此<a href="generic-types">泛型</a><mark style="color:yellow;">馬上變為單型別的具體型別</mark>。</p></td></tr></tbody></table>

{% tabs %}
{% tab title="💈 範例一" %}
:point\_right: [roles](https://lochiwei.gitbook.io/ios/master/term/roles "mention")：不同角色(實現者、使用者)對型別的不同控制權

<details>

<summary><span data-gb-custom-inline data-tag="emoji" data-code="1f477">👷</span> 實現者 (implementer)</summary>

<pre class="language-swift"><code class="lang-swift">// custom protocol
<strong>protocol MyShape {
</strong>    func area() -> Double
}

// custom types conforming to MyShape
struct MyCircle: MyShape {
    var radius: Double
    func area() -> Double { .pi * radius * radius }
}

struct MySquare: MyShape {
    var size: Double
    func area() -> Double { size * size }
}

// return type: opaque type (some)
func makeCircle() -> some MyShape {  // ⭐️ 返回值具體型別：`MyCircle`
    return MyCircle(radius: 10)      // ⭐️ 決定者：實現者
}                                    // ⭐️ 決定期：編譯期 (compile time) 

// return type: boxed protocol type (any)
func makeAnyShape() -> any MyShape { // ⭐️ 返回值具體型別：(動態決定)
    let n = Int.random(in: 1...6)    // ⭐️ 決定者：使用者
    return (n % 2 == 0)              // ⭐️ 決定期：執行期 (run time)
        ? MyCircle(radius: 10)      
        : MySquare(size: 4)
}                                     

// generic type
struct Container&#x3C;T> {
    var value: T
}
</code></pre>

</details>

<details>

<summary><span data-gb-custom-inline data-tag="emoji" data-code="1f9d1-1f4bc">🧑‍💼</span> 使用者 (user)</summary>

```swift
let shape = makeCircle()        // ⭐️ 使用者：只知道返回值是 `some MyShape`
print(shape.area())             // ⭐️ 使用者：可使用 `MyShape` 的方法

let a = Container(value: 42)    // ⭐️ 泛型的具體型別：`Container<Int>`
                                // ⭐️ 決定者：使用者
                                // ⭐️ 決定期：編譯期 (compile time)
```

</details>
{% endtab %}

{% tab title="💈 範例二" %}

```swift
// type of property
// -------------------------------
var a: View = Text("Hello")        // ⛔：`View` has associatedtype 'Body`
var b: some View = Text("Hello")   // ✅ opaque type
var c: any View = Text("Hello")    // ✅ existential type
```

:point\_right: [associated-type](https://lochiwei.gitbook.io/ios/swift/type/category/protocol/associated-type "mention")\
:point\_right: [some](https://lochiwei.gitbook.io/ios/swift/type/category/some-any-generics/some "mention")

<pre class="language-swift"><code class="lang-swift">// return type (of computed property)
// -------------------------------------

<strong>let n = Int.random(in: 1...5)
</strong>
// ✅ OK (same type, homogeneous)
var a: some View {
    if n % 2 == 0 { Text("Even") }
    else { Text("Odd") }
}

// ⛔ NG! (Text ≠ Label)
var b: some View {
    if n % 2 == 0 { Text("Even") }
    else { Label("Hello", systemImage: "bolt.fill") }
}

// ✅ OK (heterogeneous, implicit type erasure)
var c: any View {
    if n % 2 == 0 { Text("Even") }
    else { Label("Hello", systemImage: "bolt.fill") }
}
</code></pre>

:point\_right: [erasure](https://lochiwei.gitbook.io/ios/swift/type/erasure "mention")

```swift
// homogeneous vs heterogeneous collection
var a: [some Shape] = [Circle(), Circle()]    // ✅ OK  (homogeneous)
var a: [some Shape] = [Circle(), Capsule()]   // ⛔ NG! (Circle ≠ Capsule)
var a: [any Shape] = [Circle(), Capsule()]    // ✅ OK  (heterogeneous)
```

{% endtab %}

{% tab title="📘 手冊" %}

* [Swift](https://docs.swift.org/swift-book/documentation/the-swift-programming-language) ⟩&#x20;
  * [Opaque and Boxed Protocol Types](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/opaquetypes/) ⟩&#x20;
    * [Boxed Protocol Type](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/opaquetypes/#Boxed-Protocol-Types) (any)
  * [Types](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/types) ⟩&#x20;
    * [Opaque Types](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/types#Opaque-Type) (some)
    * [Boxed Protocol Types](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/types#Boxed-Protocol-Type) (any)
      {% endtab %}

{% tab title="👥 相關" %}

* [some](https://lochiwei.gitbook.io/ios/swift/type/category/some-any-generics/some "mention")
* <mark style="color:orange;">existential type</mark>
* homogeneous type
* heterogeneous type
* :beginner: [roles](https://lochiwei.gitbook.io/ios/master/term/roles "mention")：不同(程式碼)角色對型別有不同的控制權。
  {% endtab %}

{% tab title="📗 參考" %}

* ChatGPT ⟩ [學習 Swift](https://chatgpt.com/share/675507f6-f118-800e-bbf4-5ca6d40ad646) ⭐️&#x20;
* Bakshi ⟩ [some and any keyword in Swift](https://www.bitsandbyteswithbakshi.com/post/some-and-any-keyword-in-swift) ⭐️ &#x20;
* SwiftSenpai ⟩ [Understanding the “some” and “any” keywords in Swift 5.7](https://swiftsenpai.com/swift/understanding-some-and-any/)&#x20;
* [Swift 5.7 中的 any 和 some](https://segmentfault.com/a/1190000042039338)
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/ios/swift/type/category/some-any-generics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
