# Sorting

[Algorithms](https://lochiwei.gitbook.io/ios/algorithms) ⟩ Sorting ⟩

{% tabs %}
{% tab title="🔴 主題" %}

* [seq.sorted](https://lochiwei.gitbook.io/ios/swift/collections/sequence/seq.sorted "mention")
* [seq.sorted-by](https://lochiwei.gitbook.io/ios/swift/collections/sequence/seq.sorted-by "mention")
* [seq.sorted-\_](https://lochiwei.gitbook.io/ios/swift/collections/sequence/seq.sorted-_ "mention") - sort by keypaths with ascending/descending orders
  {% endtab %}

{% tab title="⭐️ 重點" %}
{% hint style="info" %}
the <mark style="color:purple;">**`sorted(by:)`**</mark> function is actually <mark style="color:red;">**2 different functions**</mark>.&#x20;

* one requires <mark style="color:purple;">**`Comparable`**</mark> and uses <mark style="color:purple;">**`<`**</mark> internally.&#x20;
* the other lets you specify the <mark style="color:red;">**sorting logic**</mark> directly (<mark style="color:purple;">**`Comparable`**</mark> conformance <mark style="color:orange;">**not required**</mark>).&#x20;

... this convenience sorting by `keyPath` would still require 2 functions.

👉 [Reference default comparison function as a function parameter](https://stackoverflow.com/a/60829002/5409815)
{% endhint %}
{% endtab %}

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

* [x] Sundell ⟩ [Sorting Swift collections](https://www.swiftbysundell.com/articles/sorting-swift-collections/)  ⭐️
* [ ] Sarun ⟩&#x20;
  * [ ] [Different ways to sort an array of strings in Swift](https://sarunw.com/posts/different-ways-to-sort-array-of-strings-in-swift/)
  * [ ] [How to sort by multiple properties in Swift](https://sarunw.com/posts/how-to-sort-by-multiple-properties-in-swift/)
    {% endtab %}

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

* Standard Lib  ⟩  Collections  ⟩  [Sequence](https://developer.apple.com/documentation/swift/sequence)
  * [sorted()](https://developer.apple.com/documentation/swift/sequence/1641066-sorted) - Element: <mark style="color:red;">**Comparable**</mark>
  * [sorted(by:)](https://developer.apple.com/documentation/swift/sequence/2907222-sorted)
* [Swift](https://developer.apple.com/documentation/swift)  ⟩  [Array](https://developer.apple.com/documentation/swift/array)  ⟩ &#x20;
  * [sort()](https://developer.apple.com/documentation/swift/array/1688499-sort) - sort **in place**. Element: <mark style="color:red;">**Comparable**</mark>
  * [sort(by:)](https://developer.apple.com/documentation/swift/array/2296801-sort) - sort **in place**.
    {% endtab %}

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

* [comparable](https://lochiwei.gitbook.io/ios/swift/type/category/protocol/comparable "mention")
* [comparable-enums](https://lochiwei.gitbook.io/ios/swift/type/category/basic/enum/comparable-enums "mention")
  {% endtab %}
  {% endtabs %}
