Home > Blockchain >  How to filter out X largest values of struct
How to filter out X largest values of struct

Time:09-27

I have a struct that looks like this:

struct stats: Identifiable {
  var id = UUID().uuidString
  var category: String
  var amount: Int
  var name: String
  var animate: Bool = false
}

static var array:[stats] = []

An array containing this struct gets very quickly populated and I want to filter out the X largest arrays inside the struct depending on the value of the amount. So the top X amount-values inside the struct. Do anyone know how to do this?

Thanks in advance :)

CodePudding user response:

Assuming you want the first 3 stats structs from an array of stats structs, you could use code like this:

struct stats: Identifiable {
    var id = UUID().uuidString
    var category: String
    var amount: Int
    var name: String
    var animate: Bool = false
}

var array:[stats] = [
    stats(category: "noises", amount: 12, name: "snork"),
    stats(category: "noises", amount: 3, name: "giggle"),
    stats(category: "noises", amount: 1, name: "whimper"),
    stats(category: "colors", amount: 7, name: "blue"),
    stats(category: "colors", amount: 2, name: "red"),
    stats(category: "pencils", amount: 6, name: "Number Two"),
    stats(category: "pencils", amount: 4, name: "Dixon Ticonderoga"),
]

let sorted = array.sorted { (lhv, rhv) -> Bool in
    return lhv.amount < rhv.amount
}

let firstThree = sorted.suffix(3)
firstThree.forEach {
    print($0)
}

That prints:

stats(id: "80B9522E-79A2-4332-8C5B-2B6B7EAD1F30", category: "pencils", amount: 6, name: "Number Two", animate: false)
stats(id: "0C90AD31-61B3-4174-B5FA-984CE8AD0474", category: "colors", amount: 7, name: "blue", animate: false)
stats(id: "0A8D6736-8494-4469-973E-2DBF01F569B3", category: "noises", amount: 12, name: "snork", animate: false)
  • Related