Quickly reduce the tuple array in

Is there a way with which I can call the reduction function in an array of tuples to find the maximum value?

for instance

struct Gate{ var maxedOpenGates = 1 var GatesOpen : [(openOrdered : Int, gateNum : Int )] = [] init(defaultSelected : Int = 0){ GatesOpen.append(openOrdered : 1, gateNum : defaultSelected) } private func manipulateGates(gates : [SegmentButton]){ for i in GatesOpen{ gates[i.gateNum].toggleSelected() } } mutating func openGate(index : Int, buttons : [SegmentButton]){ if GatesOpen.count < maxedOpenGates{ GatesOpen.append( openOrdered: GatesOpen.count , gateNum: index) }else{ //////Finding the gate that was Opened the longest//// let lastGate = GatesOpen.reduce(Int.min,{ max($0,$1) }) } manipulateGates(buttons) } } 

where I'm trying to reduce based on openOrdered

  let lastGate = GatesOpen.reduce(Int.min,{ max($0,$1) }) 
+5
source share
2 answers

Yes, you can reduce the tuple array just like any other array. The arguments to the combine function are array elements in your case "gate tuples". And if the result of reducing the array should also be a gate tuple, then the source element and the result of the union function should also be of this type:

 let lastGate = gatesOpen.reduce(gatesOpen[0]) { $0.openOrdered < $1.openOrdered ? $1 : $0 } 

Of course, for this array to work, there must be at least one element. To avoid unnecessarily comparing gatesOpen[0] with yourself you can change it to (edited after @Airspeed comment):

 let lastGate = dropFirst(gatesOpen).reduce(gatesOpen[0]) { $0.openOrdered < $1.openOrdered ? $1 : $0 } 
+4
source

Using a closure with a reduction function,

  //////Finding the gate that was Opened the longest//// let intitalValue = (Int.min,Int.min) let lastGate: (openOrdered: Int, gateNum: Int) = GatesOpen.reduce(intitalValue){ (longestOpenGate: (openOrdered: Int, gateNum: Int), gate) in if(longestOpenGate.openOrdered < gate.openOrdered) { return gate; } else { return longestOpenGate; } } let lastGateNumber = lastGate.gateNum; 

Or

 let lastGate: (openOrdered: Int, gateNum: Int) = GatesOpen.reduce(intitalValue){ $0.openOrdered < $1.openOrdered ? $1 : $0 } let lastGateNumber = lastGate.gateNum; 
+3
source

All Articles