extension Array where Element : Hashable { func modalValue() -> Self.Element? { // populate a dictionary of element vs count var dict: [Self.Element : Int] = [:] self.forEach { v in if let count = dict[v] { dict[v] = count + 1 } else { dict[v] = 1 } } // find the maximum count, and then return the first key that has that count if let max = dict.values.max() { for kv in dict { if kv.value == max { return kv.key } } } return nil } }