Find maximum and minimum values from a Swift array of integer type

In this Swift programming tutorial, you are going to learn how to find the maximum and minimum values from an integer-type array.

Swift already comes with the in-built max() and min() methods. We can use these methods to perform our tasks. Both of these methods work similarly.

The max method will help us to find the largest value. On the other hand, the min method will get the integer smallest value.

Find maximum value from a Swift array

Suppose, we have an integer type array that contains some integer type values in it. Now we have to find the maximum value among the items.

Below is the code example in Swift for getting the maximum value from the array:

let valuesArray = [13, 22, 54, 7, 19]

let maxVal = valuesArray.max()

print( "maximum value is \(maxVal!)" )

In the above code, we have used the Swift max() method to get the maximum value from our array.

Finding the minimum value from a Swift array

Just like the above example, we can also get the minimum array item value. In this case, we have to use the min() method. Below is how we can do it:

let valuesArray = [13, 22, 54, 7, 19]

let maxVal = valuesArray.min()

print( "maximum value is \(maxVal!)" )

You can see that, in both of the above programs, we have used the “!” in our program. This is because we have to get only the integer value.

I hope, you have understood how to use the max() and the min() method in Swift programming.