To find the mode of all values in a Swift Dictionary
(also known as a Map
), you can use the following code:
main.swift436 chars17 lines
Here, the mode
function takes in a dictionary as input and returns an array of the mode value(s) in the dictionary. It works by first creating an array of all the values in the dictionary, then creating a dictionary called counts
where the keys are the values in the array and the values are their frequency count.
Then, the function uses the max
method of the counts
dictionary's values to find the highest frequency count, which gives us the count of the mode value(s). Finally, the function filters the dictionary for all the keys (values in the original array) that have the max count, and returns them as an array.
Note that this code assumes that the dictionary contains Int
values -- if your map uses a different data type, you'll need to adjust the code accordingly.
gistlibby LogSnag