> 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/swift/collections/sequence/seq.grouped-by.md).

# seq.grouped(by:)

{% tabs %}
{% tab title=".grouped()" %}
:point\_right: [replit](https://replit.com/@pegasusroe/seqgroupedby)

```swift
// ⭐️ seq.grouped(by:)
extension Sequence {
    public func grouped<Key>(
        by keyForValue: (Element) -> Key
    ) -> [Key: [Element]] 
    {
        return Dictionary(grouping: self, by: keyForValue)
    }
}

```

{% endtab %}

{% tab title="💈範例" %}
:point\_right: [paiza.io](https://paiza.io/projects/x7txFa-t-6_tV3j33khgiA?language=swift)

```swift
// `Dictionary` conforms to `Sequence`
let dict = [                                // Dictionary<Key, Value>
    "Sam": 79, "Joe": 5, "Mary": 18,        // Key     = String
    "Tom": 5, "Alex": 82, "Nancy": 1        // Value   = Int
]                                           // Element = (key: Key, value: Value) ⭐️

// ⭐️ seq.grouped(by:)
let grouped = dict.grouped { $0.value }     // ⭐️ grouped by element's `value`
// ⭐️ 也可寫成： dict.grouped(by: \.value)    // ⭐️ keypath as functions
/*
[
    18: [(key: "Mary" , value: 18)], 
    5 : [(key: "Tom"  , value:  5), (key: "Joe", value: 5)], 
    82: [(key: "Alex" , value: 82)], 
    1 : [(key: "Nancy", value:  1)], 
    79: [(key: "Sam"  , value: 79)]
]
*/

// ⭐️ Dictionary(grouping:by:)
let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]

let studentsByFirstLetter = Dictionary(
    grouping: students, 
    by: { $0.first! }
)
/// [
///   "E": ["Efua"],
///   "K": ["Kofi", "Kweku"],
///   "A": ["Abena", "Akosua"]
/// ]
```

{% endtab %}

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

* SwiftUI Tutorials ⟩ [Composing Complex Interfaces](https://developer.apple.com/tutorials/swiftui/composing-complex-interfaces) ⟩
  * [Sec. 2: Create a Category List](https://developer.apple.com/tutorials/swiftui/composing-complex-interfaces#Create-a-Category-List) - Step 2.
* [Swift](https://developer.apple.com/documentation/swift)
  * [Dictionary](https://developer.apple.com/documentation/swift/dictionary) ⟩ [.init(grouping:by:)](https://developer.apple.com/documentation/swift/dictionary/3127163-init)
  * [Sequence](https://developer.apple.com/documentation/swift/sequence) ⟩ [.enumerated()](https://developer.apple.com/documentation/swift/sequence/1641222-enumerated)
    {% endtab %}

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

* [List](/ios/swiftui/lists/list.md)
* [Sequence](/ios/swift/collections/sequence.md)
* [ranking list](/ios/algorithms/sort/ranking-list.md)
* [Key Path Expressions as Functions](/ios/features/key-path/key-path-as-functions.md)
  {% endtab %}

{% tab title="🗣 討論" %}

* [Swift ranking dictionary](https://stackoverflow.com/a/56513861/5409815) - build ranking list from scores
  {% endtab %}
  {% endtabs %}
