# sort using key paths

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

```swift
// ⭐️ custom sorting using key paths
extension Sequence {
    func sorted<T: Comparable>(
        by    keyPath: KeyPath<Element, T>,
        // ⭐️ in ascending order by default.
        using compare: (T, T) -> Bool = (<)    // ⭐️ 預設運算(括號為必要)
    ) -> [Element] {
        sorted { a, b in
            compare(a[keyPath: keyPath], b[keyPath: keyPath])
        }
    }
}

todolist.sorted(by: \.date)
todolist.sorted(by: \.item).map(\.item)
todolist.sorted(by: \.item, using: >).map(\.item)  // descending order

```

{% endtab %}

{% tab title="TodoItem" %}

```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="👥 相關" %}

* [key-path](https://lochiwei.gitbook.io/ios/features/key-path "mention")
* [seq.sorted-\_](https://lochiwei.gitbook.io/ios/swift/collections/sequence/seq.sorted-_ "mention")  ⭐️ - sort by **multiple** **keypaths**
  {% endtab %}
  {% endtabs %}
