/* Three versions of a histogram function showing the various uses of optionals. The third is perhaps the best. */ /** Compute a histogram for a list of names. - Parameter names: array of data to compute over - Returns: a map from name to count, reflecting how many times it appeared in names */ func histogram(names : [String]) -> [String:Int] { var counts = [String:Int]() for name in names { let value = counts[name] if value != nil { counts[name] = value! + 1 } else { counts[name] = 1 } } return counts } /** As above, but uses if-let instead of explicit nil tests. */ func histogram2(names : [String]) -> [String:Int] { var counts = [String:Int]() for name in names { if let value = counts[name] { counts[name] = value + 1 } else { counts[name] = 1 } } return counts } /** As above, but uses ?? to provide a default value. */ func histogram3(_ names : [String]) -> [String:Int] { var counts = [String:Int]() for name in names { let value = counts[name] ?? 0 counts[name] = value + 1 } return counts } // Example usage print(histogram3(["A", "A", "B", "C", "A", "C"]))