gpt4 book ai didi

Swift 减少元组数组

转载 作者:搜寻专家 更新时间:2023-10-30 22:09:00 25 4
gpt4 key购买 nike

有没有一种方法可以调用元组数组的 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)
}
}

我试图根据 openOrdered

减少的地方
 let lastGate = GatesOpen.reduce(Int.min,{ max($0,$1) })

最佳答案

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

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

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

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

关于Swift 减少元组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29787946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com