How do you find a maximum value in a Swift dictionary?
let maximum = data.reduce(0.0) { max($0, $1.1) }
Just a quick way using reduce
.
or:
data.values.max()
Output:
print(maximum) // 5.828
How do you find the top 3 maximum values in a Swift dictionary?
The max method can only return a single value. If you need to get the top 3 you would need to sort them in descending order and get the first 3 elements using prefix method
let greatestChampion = champions.sorted { $0.value > $1.value }.prefix(3)
print(greatestChampion)
This will print
[(key: "Neeko", value: 25), (key: "Ekko", value: 20), (key: "Ahri", value: 10)]
Find a maximum in array of dictionaries
Here's one possible solution using Array max(by:)
.
Note that this example uses a lot of crash operators (!
). Safely unwrap as needed for your real code:
let data: [[String: Any]] = [
["date":Date(), "value":8],
["date":Data(), "value":13],
]
let maxEntry = data.max { ($0["value"] as! Int) < ($1["value"] as! Int) }!
let maxValue = maxEntry["value"] as! Int
Another option is to use map
and max
:
let maxValue = data.map { $0["value"] as! Int }.max()!
All these examples assume the array won't be empty and that each dictionary has a valid Int
value for the "value"
key. Adjust the code as needed if these assumptions are not valid.
How can I get the largest value from an integer array in a dictionary of arrays
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var largest_kind : String? =nil
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largest_kind = kind
}
}
}
Swift get max key from and sort
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)
How does the function of finding the maximum in the dictionary work?
someDictionary
is a Dictionary. A Dictionary is a kind of Sequence (see the "Default Implementations" section of Dictionary to know that it's a Sequence). Sequences provide the method max(by:)
, which:
Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
Swift has trailing-closure syntax, so you can write .max {...}
instead of .max(by: { ... })
. The two syntaxes are identical, but most developers use trailing-closure syntax when possible.
The parameter is defined as:
areInIncreasingOrder
A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.
The Element of Dictionary as a Sequence is a tuple (key: Key, value: Value)
, so this is the type that is passed to areInIncreasingOrder
.
The closure defines two parameters, a
and b
, each of type (key: Key, value: Value)
. It returns whether a.value
is less than b.value
. Swift allows 1-statement closures to omit the return
.
This paragraph is somewhat technical and you may want to skip it. The TL;DR is that max
returns the maximum element according to your closure. Provided the closure obeys the rules defined in the docs, the max
algorithm will return the maximum element, for a specific definition of "maximum," which is that there is no element in the sequence that is ordered after this one according to areInIncreasingOrder
. This pedantic definition especially matters when there are incomparables in the list. Equal elements are (somewhat strangely IMO) defined as "incomparable" in that neither is before the other. This also matters for values like NaN.
This will return a maximum element, or nil
if the Sequence is empty. (The docs say "the" maximum element, but in the case of incomparable elements, it is not promised which one will be returned.)
maxValueOfSomeDictionary
is of type (key: String, value: Int)?
, an optional version of the Element of the Dictionary, since it may be a value or it may be nil
.
maxValueOfSomeDictionary!
converts an Optional into its wrapped value, or crashes if the Optional is nil. This then prints the .value
of that.
To see precisely how max
operates, you can read the default implementation in stdlib.
Related Topics
Post Requests in Alamofire Parameter Encoding Returning Get Responses
Swift Error: Cannot Convert of Type '()' to Specified Type 'Bool'
Printed Double Value Differs from Originally Set Value
How to Resume a Published Timer in Swiftui After Navigating to a Different Page
Exc_Bad_Instruction Only in iPhone 5 Simulator
Need Explaining on the Double Label Function Declaration
Swift Can Not Save .M3U8 File to Gallery
Convert Integer to Roman Numeral String in Swift
Diddiscoverservices Is Not Being Called After a Ble Connection
Should I Remove All Skspritenodes and Labels When I Switch from One Node to Another
How to Add Characters into Dateformatter
Nsurlsession Datataskwithrequest Not Being Called
Loading Uiviewcontroller from Instantiateviewcontrollerwithidentifier - Nil Outlets
Swift Updating Screen in Between Steps of While Loop
Stateobject as Parameter for Another Object in Init()
Error on Adding Uinavigationbar Button with Image
Accessing Actor Properties Synchronously from Task-Less Context