find the range of all elements in an array in swift

To find the range of all elements in an array in Swift, you can use the min() and max() functions to obtain the lowest and highest values of the array, respectively. Here's an example:

main.swift
let array = [1, 2, 3, 4, 5]
let minVal = array.min() // returns 1
let maxVal = array.max() // returns 5

if let minVal = minVal, let maxVal = maxVal {
    let range = minVal...maxVal // creates a ClosedRange<Int> instance with the range
    print(range) // output: 1...5
}
273 chars
9 lines

In this example, we first define an array array with some values. We then use the min() and max() functions to obtain the lowest and highest values of the array, respectively. Since these functions return optional values due to the possibility of the array being empty, we use optional binding (if let...) to safely unwrap the values. Finally, we create a ClosedRange<Int> instance from the obtained range using the ... operator, and print it to the console.

related categories

gistlibby LogSnag