---
description: >-
  讓一般的物件可以像函數一樣，只要給它一些參數，它就可以回傳一些別的東西，用法類似 subscript，只是把 instance[index] 改為
  instance(index) 而已。
---

# Calling Types As Functions

This feature supports **argument labels** and **parameter types**, **throws** and **rethrows**, and is not constrained to primary type declarations. Furthermore, it is possible to define **multiple** **callAsFunction** methods on a single type, and Swift will handle which one to call, similar to a simple **overloading**.

{% tabs %}
{% tab title="📦 User" %}
```swift
struct Adder {
    var base: Int
    // ⭐️ callAsFunction 
    func callAsFunction(_ x: Int) -> Int {
        return base + x
    }
}
```
{% endtab %}

{% tab title="💈 範例 " %}
```swift
let add3 = Adder(base: 3)
add3(10)                     // 13 == adder.callAsFunction(10)
```
{% endtab %}

{% tab title="📘 參考 " %}
* [x] [Swift 5.2 Brings callAsFunction, Subscript with Default Arguments, and More](https://www.infoq.com/news/2020/02/swift-5-2/) - InfoQ
* [ ] [https://www.raywenderlich.com/9224115-what-s-new-in-swift-5-2](https://www.raywenderlich.com/9224115-what-s-new-in-swift-5-2)
* [ ] [SE-0253: Callable values of user-defined nominal types](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md)
* [ ] [Swift: subscript vs. callAsFunction](https://stackoverflow.com/questions/64289045/swift-subscript-vs-callasfunction) - StackOverflow
{% endtab %}

{% tab title="⚙️ 執行 " %}
{% embed url="https://paiza.io/projects/e/Y2WzaopekFw_G7_ZH0c0tQ?theme=twilight" %}
💈範例
{% endembed %}


{% endtab %}
{% endtabs %}

{% hint style="info" %}
從這個語法看起來，這個就有點像 **subscript** 一樣，只是把 subscript 的 somethin&#x67;**\[index]** 改為 somethin&#x67;**(index)** 而已。
{% endhint %}

\#todo: #if swift>=5.2 寫入 CGRect(x, y)
