LoginSignup
12
5

More than 5 years have passed since last update.

Swift:配列のmax(by:),min(by:)の使い方

Last updated at Posted at 2018-11-19

カスタムクラスや構造体,タプルなどの配列の最大値,最小値を取得する時に使えるmax(by:)min(by:)
使い方に注意点があったので備忘録

var items: [(name: String, number: Int)] = [("banana", 234), ("apple", 423), ("grape", 142)]

let max = items.max(by: { (a, b) -> Bool in
    return a.number < b.number //ここの不等号の向き要注意!
})

let min = items.min(by: { (a, b) -> Bool in
    return a.number < b.number
})

Swift.print("\(max), \(min)")

// -> ("apple", 423), ("grape", 142)

※maxの時の不等号の向きに要注意です!

12
5
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
12
5