37
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[iOS8] Swiftで配列をソート(昇順・降順・逆さま)する方法

Posted at

Swiftで配列をソートしたい時に役立つ関数を、サンプルコードを利用して説明します。
以下、3通りのソートサンプルコードです。

・昇順

var arr = [3, 2, 5, 1, 4, 0] // [3,2,5,1,4,0]
arr.sort { $0 < $1 }         // [0,1,2,3,4,5]

・降順

var arr = [3, 2, 5, 1, 4, 0]  // [3,2,5,1,4,0]
arr.sort { $1 < $0 }          // [5,4,3,2,1,0]

・逆さま

var arr = [3, 2, 5, 1, 4, 0]      // [3,2,5,1,4,0]
let reversedArray = arr.reverse() // [0,4,1,5,2,3]

[異なる点]
昇順と降順
・配列の値を比較して整理されます。
・配列自身をソートします。

逆さま(reverse)
・key(id)によって値が入れ替えられます。
・ソートは新規の配列に入れられます。

37
34
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
37
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?