> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/features/key-path/key-path-as-functions.md).

# Key Path Expressions as Functions

{% hint style="info" %}
able to use the <mark style="color:red;">**key path expression**</mark> <mark style="color:purple;">**\Root.value**</mark> wherever <mark style="color:red;">**functions**</mark> of <mark style="color:purple;">**(Root) -> Value**</mark> are allowed. <mark style="color:orange;background-color:yellow;">Swift 5.2</mark>&#x20;
{% endhint %}

{% tabs %}
{% tab title="💈範例 " %}
:point\_right: [paiza.io](https://paiza.io/projects/e/Y2WzaopekFw_G7_ZH0c0tQ?theme=twilight)

```swift
struct User {
    let email: String
    let isActive: Bool
}

let users = [
    User(email: "joe@me.com", isActive: true),
    User(email: "joy@me.com", isActive: false)
]

// ⭐️ key path as functions
// 1. \.email    = { $0.email    }
// 2. \.isActive = { $0.isActive }
//                     ╭──1──╮
let emails = users.map(\.email)    // (User) -> String
// ["joe@me.com", "joy@me.com"]

//                             ╭───2────╮
let activeUsers = users.filter(\.isActive)    // (User) -> Bool
// [User(email: "joe@me.com", isActive: true)]

// ⭐️ subscript <---> key path 
// user[keyPath: \User.isActive] == user.isActive 
// let userStates = users.map { user in user[keyPath: \User.isActive] } // == users.map { $0.isActive }
     
```

{% endtab %}

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

* [x] InfoQ ⟩ [Swift 5.2 Brings callAsFunction, Subscript with Default Arguments, and More](https://www.infoq.com/news/2020/02/swift-5-2/)
* [ ] Swift Evolution ⟩ [SE-0249: Key Path Expressions as Functions](https://github.com/apple/swift-evolution/blob/master/proposals/0249-key-path-literal-function-expressions.md)
* [ ] 彼得潘 ⟩ [Swift 方便存取 property 的 KeyPath & KeyPath as Functions](https://medium.com/彼得潘的-swift-ios-app-開發問題解答集/swift-方便存取-property-的-keypath-keypath-as-functions-85778939c2fd)
  {% endtab %}

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

* [seq.grouped(by:)](/ios/swift/collections/sequence/seq.grouped-by.md)
  {% endtab %}
  {% endtabs %}
