2
3

More than 3 years have passed since last update.

【Swift / 多次元配列】structを型に持った配列をソートする

Posted at

コロナウイルスの感染状況がWebAPIで公開されていたので、
それに関する実装の時のコードになります。

型の中身はこんな感じ

struct Prefecture: Codable {
    var id: Int
    var name_ja: String  //都道府県
    var cases: Int //陽性者数
    var deaths: Int //死者数
    var pcr: Int //PCR検査人数
}

たったの3行でソートができる

var array:[Prefecture] = []
array.sort(by: { a, b -> Bool in
    return a.cases > b.cases
})

aとbは配列の中身の2要素で、それぞれが持つプロパティを
演算、trueかfalseをreturnしてそれに応じてソートしてくれる。

2
3
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
2
3