LoginSignup
0
2

More than 1 year has passed since last update.

Swift 複数の条件ソート方法

Posted at

複数条件でソートする方法を書きます。

対象読者

Swift初学者

辞書の複数条件ソート

let dictionary = ["b": 2, "c": 3, "a": 1, "d": 1, "z": 1]
// 1.value昇順ソート
// 2.同じvalue値の時ZtoA降順ソート
let sortedDictionary = dictionary.sorted { (first, second) -> Bool in
    if first.value != second.value {
        return first.value < second.value
    } else {
        return first.key > second.key
    }
}
for (key,value) in sortedDictionary{
    print("\(key) \(value)")
}
// 出力
z 1
d 1
a 1
b 2
c 3

条件部分を三項演算子で書くと行数を減らせる。

let sortedDictionary = dictionary.sorted { (first, second) -> Bool in
    return first.value != second.value ? first.value < second.value : first.key > second.key
}

構造体のソート

struct Person {
    let name: String
    let age: Int
    let height: Double
}

let people = [
    Person(name: "Alice", age: 25, height: 162.5),
    Person(name: "Bob", age: 30, height: 180.0),
    Person(name: "Charlie", age: 20, height: 170.0),
    Person(name: "David", age: 35, height: 165.0)
]

// 名前でソートし、名前が同じ場合は年齢でソートし、年齢が同じ場合は身長でソート
let sortedPeople = people.sorted(by: { (p1, p2) -> Bool in
    if p1.name != p2.name {
        return p1.name < p2.name
    } else if p1.age != p2.age {
        return p1.age < p2.age
    } else {
        return p1.height < p2.height
    }
})

print(sortedPeople)
// [Main.Person(name: "Alice", age: 25, height: 162.5), Main.Person(name: "Bob", age: 30, height: 180.0), Main.Person(name: "Charlie", age: 20, height: 170.0), Main.Person(name: "David", age: 35, height: 165.0)]

条件部分を比較したいプロパティをタプルにまとめて書くことで、
複数のプロパティでソートすることができます。

let sortedPeople = people.sorted {
    ($0.name, $0.age, $0.height) < ($1.name, $1.age, $1.height)
}
0
2
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
0
2