Vlad78
Vlad78

Reputation: 133

Swift get max key from and sort

I have var dataDictionary = [[String:Any]]() and data inside :

[["quant": 10, "name": "..."], 
["quant": 20, "name": "..."], 
["quant": 25, "name": "..."],
["quant": 27, "name": "..."],
["quant": 30, "name": "..."],
["quant": 30, "name": "..."],
["quant": 20, "name": "..."],
["quant": 40, "name": "..."],
["quant": 15, "name": "..."],
...]

I want to get max from all "quant" and then create func to make a selection int to maxKey and print For example need get from 30 to maxKey and get :

[["quant": 30, "name": "..."],
["quant": 30, "name": "..."],
["quant": 40, "name": "..."]]

Im try to get max like this:

let maxVal = dataDictionary.max { a, b in a.value < b.value }

but have error

Value of type '[String : Any]' has no member 'value'

Upvotes: 1

Views: 1185

Answers (4)

Milan Nos&#225;ľ
Milan Nos&#225;ľ

Reputation: 19757

You have to access "quant" value through subscription:

var dataDictionary = [[String:Any]]()
let maxVal = dataDictionary.max { (lhs, rhs) -> Bool in
    let leftValue = lhs["quant"] as? Int ?? 0
    let rightValue = rhs["quant"] as? Int ?? 0
    return leftValue < rightValue
}

Upvotes: 1

Ankit Jayaswal
Ankit Jayaswal

Reputation: 5679

In your tried mechanism,

let maxVal = dataDictionary.max { a, b in a.value < b.value }

a, b are dictionaries of type [String: Any] which do not have .values properties. So, to find max quant dictionary, you should use:

let maxVal = dataDictionary.max { a, b in (a["quant"] as! Int) < (b["quant"] as! Int) }

If you wished to get all the dictionaries having quant more than or equal to specific value, you have to use:

let quantLimit: Int = 30
let maxValFrom30 = dataDictionary.filter({ ($0["quant"] as! Int) >= quantLimit })

Upvotes: 0

Jogendar Choudhary
Jogendar Choudhary

Reputation: 3494

You are doing max on the array so You have to access quant from keyValue pair like this way:

    dataDictionary.max { (a, b) -> Bool in
        return a["quant"] as! Int > b["quant"] as! Int
        //Or with optional
        return a["quant"] as? Int ?? 0 > b["quant"] as? Int ?? 0

     }

OtherWise when you are doing it on [String: Any] then you can do like as same as you are doing

let greatestDict = dataDictionary.max { a, b in a.value < b.value }
print(greatestDict)

Upvotes: 0

Karthikeyan Bose
Karthikeyan Bose

Reputation: 1274

try this

 dataDictionary.sort { (v1, v2) -> Bool in
  return v1["quant"] as? Int ?? 0 <  v2["quant"] as? Int ?? 0
}
let min = 30
let max = dataDictionary.last!["quant"] as? Int ?? min
let filtered = dataDictionary.filter({(dict) in
  let valueToCompare = dict["quant"] as! Int
  return valueToCompare >= min && valueToCompare <= max
})
print(filtered)

Upvotes: 1

Related Questions