Swift减少一系列元组

Moo*_*Cow 6 swift

有没有办法可以在元组数组上调用reduce函数来查找最大值?

例如

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图根据openOrdered减少的地方

 let lastGate = GatesOpen.reduce(Int.min,{ max($0,$1) })
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 5

是的,您可以像任何其他数组一样减少元组数组。组合函数的参数是数组的元素,在您的例子中是“门元组”。如果减少数组的结果也应该是门元组,那么组合函数的初始元素和结果也必须是该类型:

let lastGate = gatesOpen.reduce(gatesOpen[0]) {
        $0.openOrdered < $1.openOrdered ? $1 : $0
}
Run Code Online (Sandbox Code Playgroud)

当然,数组必须至少有一个元素才能起作用。为了避免与自身进行不必要的比较,gatesOpen[0]您可以将其更改为(在@Airspeed的评论后编辑):

let lastGate = dropFirst(gatesOpen).reduce(gatesOpen[0]) {
    $0.openOrdered < $1.openOrdered ? $1 : $0
}
Run Code Online (Sandbox Code Playgroud)