find the range of all values in a map in swift

One way to find the range of all values in a Map in Swift is to use the min() and max() functions on the values property of the Map. Here's an example:

main.swift
let myMap = ["a": 3, "b": 7, "c": 2, "d": 5]
let values = myMap.values.compactMap{ $0 }
if let minValue = values.min(), let maxValue = values.max() {
    let range = minValue...maxValue
    print("The range of values in the map is: \(range)")
} else {
    print("The map is empty")
}
284 chars
9 lines

In this example, we first create a Map called myMap with four key-value pairs. Then, we extract the values of the map using the values property, which returns a LazyMapCollection of optional values. To remove the optionals, we use the compactMap function, which returns a non-optional array of integers. We then use optional binding (if let) to safely extract the minimum and maximum values from the array. Finally, we create a ClosedRange with the minimum and maximum values, and print it to the console.

Note that if the map is empty, values.min() and values.max() will both return nil, so we need to handle that case separately.

gistlibby LogSnag