LoginSignup
28
27

More than 5 years have passed since last update.

Swiftで複数の条件で配列をソートする

Last updated at Posted at 2014-09-16

従来はNSSortDescriptorという便利な物があったので、
以下のように条件を順番に配列にして渡せば良かったのですが…

NSArray.sortedArrayUsingDescriptors
let x = NSSortDescriptor(key:"x", ascending:true)
let y = NSSortDescriptor(key:"y", ascending:true)
let z = NSSortDescriptor(key:"z", ascending:true)

let sorted = items.sortedArrayUsingDescriptors([x, y, z])

Swiftの場合は一つの関数で判定条件を書く必要があるので、若干回りくどくなります。

Array.sorted
let sorted = items.sorted { (a:Item, b:Item) -> Bool in
    if a.x == b.x {
        if a.y == b.y {
            return a.z < b.z
        } else {
            return a.y < b.y
        }
    } else {
        return a.x < b.x
    }
}

元の配列を変更してしまっていい場合は、sortを使います。

Array.sort
items.sort { (a:Item, b:Item) -> Bool in
    if a.x == b.x {
        if a.y == b.y {
            return a.z < b.z
        } else {
            return a.y < b.y
        }
    } else {
        return a.x < b.x
    }
}
28
27
2

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
28
27