Simple Swift example to find minimum and maximum values in an integer array with Italian comments for easy learning and practical use in Xcode.
// Function to find the minimum and maximum value in an array of integers
func trovaMinMax(numeri: [Int]) -> (minimo: Int?, massimo: Int?) {
// Check that the array is not empty
guard !numeri.isEmpty else {
// If it is empty, return nil for both values
return (nil, nil)
}
// Use the min() and max() methods to find the values
let minimo = numeri.min()
let massimo = numeri.max()
// Return the tuple with the found values
return (minimo, massimo)
}
// Example of using the function
let arrayDiNumeri = [12, 5, 8, 130, 44, 2, 99]
// Call the function
if let risultato = trovaMinMax(numeri: arrayDiNumeri) {
if let minVal = risultato.minimo, let maxVal = risultato.massimo {
print("Minimum value: \(minVal)")
print("Maximum value: \(maxVal)")
} else {
print("The array is empty, no minimum or maximum value available.")
}
}Swift language (version 5 or higher)
No external dependencies required
Development environment: Xcode or any IDE that supports Swift
Input: hardcoded integer array in the code
Output: console print of the minimum and maximum values