The min and max function already worked, but I don't know how to add a function for sum and average of the integer array.
Here is my code:
func minMax(array: [Int]) -> (min: Int, max: Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
let bounds = minMax(array: [8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)") //outputs min is -6 and max is 109
CodePudding user response:
let array : [Int] = [8, -6, 3, 109, 3, 71]
func foo(array : [Int]) -> (Int, Float, (Int, Int)){
let sum : Int = array.reduce(0, )
let avg : Float = Float(sum)/Float(array.count)
let min : Int = array.min()!
let max : Int = array.max()!
return (sum, avg, (min, max))
}
//if u want add this nil checking inside the function
if array.count != 0{
print(foo(array: array)) // (188, 31.333334, (-6, 109))
}