Help us understand the problem. What is going on with this article?

Swift3でタプルの配列をソートする

More than 1 year has passed since last update.

忘れそうなのでメモ

通常の配列のソートについては以下を参照
[iOS8] Swiftで配列をソート(昇順・降順・逆さま)する方法

例えばこんな感じにnameとdistanceの二つのタプル配列があったとする

var List:[(name:String,distance:Int)] = [
    (name:"A",distance:13),
    (name:"B",distance:43),
    (name:"C",distance:1),
    (name:"F",distance:53),
    (name:"E",distance:53),
    (name:"D",distance:53),
]

これをdistanceの昇順に並べる際には

List.sort { (A, B) -> Bool in
            return A.distance < B.distance
        }

このAとBについては変更可能で、第一引数が前の値、第二引数が後ろの値に対応していると考えてsortに条件式を書いていく
そのあとに「.タプルの要素名」で扱う

ただしこのコードで並べ換えると以下のような並びになる
スクリーンショット 2017-10-24 11.49.45.png

これを見るとdistanceが53であるDEFの三つはnameの昇順で並び替えて欲しくなるので次のように複数の条件でソートさせた

愚直に書くと.sort
List.sort { (A, B) -> Bool in
    if A.distance == B.distance {
        return A.name < B.name
    }else if A.distance < B.distance{
        return true
    }
    return false
}

スクリーンショット 2017-10-24 11.53.00.png

これでOKのはず・・・
ただfalseを忘れるとエラー吐いてコンパイル通らないので注意
なので「return 条件式」で書くといいかもしれない

同じ内容でreturn条件式書き.sort
List.sort { (A, B) -> Bool in
    if A.distance == B.distance {
        return A.name < B.name
    }
    return A.distance < B.distance
}

以上です。

ryosuke_tamura
Twitter https://twitter.com/ryosuke_tamura wantedly https://www.wantedly.com/users/39177224
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした