find the range of a list of numbers in swift

To find the range of a list of numbers in Swift, you can use the min() and max() functions to find the smallest and largest numbers in the list, respectively. Then, you can subtract the smallest number from the largest number to get the range.

Here's an example code snippet:

main.swift
let numbers = [1, 5, 3, 9, 7, 2, 11]

let smallestNumber = numbers.min()!
let largestNumber = numbers.max()!
let range = largestNumber - smallestNumber

print("The range of the list is \(range)")
196 chars
8 lines

In this example, the output will be:

main.swift
The range of the list is 10
28 chars
2 lines

Note that the min() and max() functions return optional values, so we need to unwrap them using the ! operator to be able to subtract them.

gistlibby LogSnag