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) }
func minimum<T: Comparable>(_ array: [T]) -> T? { guard var minimum = array.first else { return nil } for element in array.dropFirst() { minimum = element < minimum ? element : minimum } return minimum } func maximum<T: Comparable>(_ array: [T]) -> T? { guard var maximum = array.first else { return nil } for element in array.dropFirst() { maximum = element > maximum ? element : maximum } return maximum }
let array = [ 8, 3, 9, 4, 6 ] array.minElement() // This will return 3 array.maxElement() // This will return 9