> 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.sorted-by.md).

# seq.sorted(by:)

```swift
// sorted(by:)
func sorted(
  by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool
) rethrows -> [Self.Element]
```

{% hint style="info" %}
用這個方法的優點是：Self.**Element** <mark style="color:blue;">**不需要**</mark>是 <mark style="color:red;">**Comparable**</mark>。
{% endhint %}

{% tabs %}
{% tab title="sort" %}

```swift
// ⭐️ 1. sort a Sequence using `sorted(by:)` method.
//     - always returns an Array.
let sorted = todolist.sorted { a, b in a.date < b.date }
```

{% endtab %}

{% tab title="todolist" %}

```swift
import Foundation  // Date

// todo item
struct TodoItem {
    let date: Date
    let item: String
}

// todo item samples
let todos = ["eat", "sleep", "play", "relax"]
let now = Date()
let nextyear = now.yearAfter

extension TodoItem {
    static let samples = (1...5).map{ _ in 
        TodoItem(
            date: .random(in: now...nextyear), 
            item: todos.randomElement()!
        )
    }
}

let todolist = TodoItem.samples
```

{% endtab %}

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

* [x] [Sorting Swift collections](https://www.swiftbysundell.com/articles/sorting-swift-collections/) - Sundell ⭐️
  {% endtab %}

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

* Standard Lib  ⟩  Collections  ⟩  [Sequence](https://developer.apple.com/documentation/swift/sequence)
  * [sorted(by:)](https://developer.apple.com/documentation/swift/sequence/2907222-sorted)
    {% endtab %}

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

* [seq.sorted()](/ios/swift/collections/sequence/seq.sorted.md)
  {% endtab %}
  {% endtabs %}
