LoginSignup
6
1

More than 3 years have passed since last update.

`array.sorted(by: key)` 的なことがしたかったんだ

Last updated at Posted at 2020-03-17

概要

キーを指定するだけでサクッとソートしてくれるようなextensionを作ってみた

実装

Sequence+KeySort.swift
extension Sequence {
    public func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] {
        sorted { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
    }

    public func sorted<T: Comparable>(by keyPath: KeyPath<Element, T?>) -> [Element] {
        sorted {
            guard let l = $0[keyPath: keyPath],
                let r = $1[keyPath: keyPath] else { return false }
            return l < r
        }
    }
}

Usage

struct Person {
    var id: Int
    var name: String
}

extension Person: CustomStringConvertible {
    var description: String { name }
}

let people: [Person] = [
    .init(id: 3, name: "Bob"),
    .init(id: 1, name: "Emma"),
    .init(id: 4, name: "Amelia"),
    .init(id: 2, name: "George"),
]

print(people.sorted(by: \.id))   // -> ["Emma", "George", "Bob", "Amelia"]
print(people.sorted(by: \.name)) // -> ["Amelia", "Bob", "Emma", "George"]
6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1