find the mode of all values in a map in swift

To find the mode of all values in a Swift Dictionary (also known as a Map), you can use the following code:

main.swift
func mode(of dict: [String: Int]) -> [Int] {
    var values = Array(dict.values)
    var counts: [Int: Int] = [:]

    for value in values {
        counts[value] = (counts[value] ?? 0) + 1
    }

    let maxCount = counts.values.max() ?? 0

    return counts.filter { $0.1 == maxCount }.map { $0.0 }
}

let dict: [String: Int] = ["apple": 2, "banana": 3, "orange": 2, "melon": 1, "grape": 3]
let modeValues = mode(of: dict) // [2, 3]

436 chars
17 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