Open2
Swift 並べ替え

並べ替え
let dates = [
"2020-01-01",
"2020-01-02",
"2020-02-02",
"2021-01-01",
"1990-12-01",
]
// 昇順
print(dates.sorted(by: <))
// ["1990-12-01", "2020-01-01", "2020-01-02", "2020-02-02", "2021-01-01"]
// 降順
print(dates.sorted(by: >))
// ["2021-01-01", "2020-02-02", "2020-01-02", "2020-01-01", "1990-12-01"]
空文字
let times = ["00:00:30", "12:30:00", "23:00:30", "03:30:00", ""]
// 昇順
print(times.sorted(by: <))
// ["", "00:00:30", "03:30:00", "12:30:00", "23:00:30"]
// 降順
print(times.sorted(by: >))
// ["23:00:30", "12:30:00", "03:30:00", "00:00:30", ""]

Object
struct Foo {
let createdAt: String
let updatedAt: String
}
let foos = [
Foo(createdAt: "2022-05-01", updatedAt: "2023-01-01"),
Foo(createdAt: "2022-04-01", updatedAt: "2023-02-01"),
Foo(createdAt: "2022-03-01", updatedAt: "2023-03-01"),
Foo(createdAt: "2022-02-01", updatedAt: "2023-04-01"),
Foo(createdAt: "2022-01-01", updatedAt: "2023-05-01"),
]
// createdAt で昇順
print(foos.sorted(by: {$0.createdAt < $1.createdAt}))
結果
[
(createdAt: "2022-01-01", updatedAt: "2023-05-01"),
(createdAt: "2022-02-01", updatedAt: "2023-04-01"),
(createdAt: "2022-03-01", updatedAt: "2023-03-01"),
(createdAt: "2022-04-01", updatedAt: "2023-02-01"),
(createdAt: "2022-05-01", updatedAt: "2023-01-01")]
あわせわざ
// createdAt は昇順 updatedAt は降順
print(foos.sorted(by: {($0.createdAt, $1.updatedAt) < ($1.createdAt, $0.updatedAt)}))
結果
[
(createdAt: "2022-01-01", updatedAt: "2023-05-01"),
(createdAt: "2022-02-01", updatedAt: "2023-04-01"),
(createdAt: "2022-03-01", updatedAt: "2023-03-01"),
(createdAt: "2022-04-01", updatedAt: "2023-02-01"),
(createdAt: "2022-05-01", updatedAt: "2023-01-01")
]